Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

ruby on rails - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...