Form_for "First argument in form cannot contain nil or be empty" error

ruby, ruby-on-rails

Solution

Assuming you are rendering this from `PostsController` and using the conventional view name, your `new` method should create a new `Post` and assign it:

def new
  @post = Post.new
end

You can use the class name (as @Yuriy suggested), but the conventional way is to instantiate a new object. That allows you to re-use the same form view for rendering errors after a save.

If you want to see how this normally looks, create a new Rails project and use the scaffold generator to create some sample code.

Problem

I cannot figure out why I'm getting this error, and exactly what it means. First argument in form cannot contain nil or be empty(Line 3) Add a new Post ``` <%= form_for @post do |f| %> //Error here <p> <%= f.label :title, 'Title' %><br/> <%= f.text_field :title %><br/> </p> <p> <%= f.label :content, 'Content'%><br/> <%= f.text_area :content %><br/> </p> <p> <%= f.submit "Add a New Post" %> </p> <% end %> ``` Controller: ``` class PostsController < ApplicationController def index @posts = Post.all end def show @post = Post.find(params[:id]) end def new @post = Post.new end def create @post = post.new(params[:post]) if @post.save redirect_to posts_path, :notice => "Your post was saved" else render "new" end end def edit end def update end def destroy end end ```

Original source