Jacob Reisner
Jacob Reisner

Reputation: 162

Rails error 'First argument in form cannot contain nil or be empty'

I've tried all different Stack posts on how to get rid of the error ' First argument in form cannot contain nil or be empty' and none of their solutions are working for me.

My app involves making posts, where users can upload images. Rather than taking image url's, I want them to be able to upload straight from their file system.

Here's my controller:

  class PostsController < ApplicationController
      before_action :all_posts, only: [:feed, :create]
      respond_to :html, :js

    def show
      @post = Post.find_by_id(params['id'])
    end


    def create
      @post = Post.create(post_params)
    end

    def new
      @post = Post.new
    end

    private

    def all_posts
      @posts = Post.all
    end

    def post_params
      params.require(:post).permit(:caption, :content, :image)
    end

  end

And new.html.erb:

<footer>
  <%= form_for @post, :html => {:multipart => true} do |f| %>
    <%= f.text_field :caption %>
    <%= f.text_field :content %>
    <%= f.file_field :image %>
    <%= f.submit %>
  <% end %>
</footer>

People keep suggesting adding @post = Post.new to the form and the action, yet none have been working for me.

Also, I've already checked my database, and I have 7 posts currently in there.

Thanks so much for the help.

Upvotes: 2

Views: 211

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

You are getting this error because your @post in nil when you call the form_for(@post,....

You have to instantiate the @post instance variable in your controller's corresponding action. As you don't have it right now, hence you are getting this error.

By looking at your rest of the code, I think you want to upload the post in your new.html.erb file NOT feed.html.erb as you mentioned in the question.

Upvotes: 1

Related Questions