Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 764
Greg Avatar asked Mar 13 '13 07:03

Greg


3 Answers

I was getting the same error message. I was just trying to get simpleform up and working and created a subdirectory within my view for testing forms when I got this error message and thought that simpleform wasn't installed.

I assumed that instance variables like @user were available to all my view files including those in lets say the @clients subdirectory and the clients/_form used for creating new clients. My assumption was incorrect as @user will evaluate to Nil when used in say the clients/_form when it's created in the @user Controller.

like image 69
Clint Feekes Avatar answered Nov 10 '22 08:11

Clint Feekes


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.

like image 17
Jim Stewart Avatar answered Nov 10 '22 09:11

Jim Stewart


Use this (not recommended). It should work.

<%= form_for Post.new do |f| %>
like image 1
Tarique Avatar answered Nov 10 '22 07:11

Tarique