我不明白为什么会收到此错误,也不知道它的确切含义。
First argument in form cannot contain nil or be empty(Line 3)
<%= 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
最佳答案
假设您从 PostsController 渲染它并使用传统的 View 名称,您的 new 方法应该创建一个新的 Post 并分配给它:
def new
@post = Post.new
end
您可以使用类名(如@Yuriy 所建议的),但传统的方法是实例化一个新对象。这允许您在保存后重新使用相同的表单 View 来呈现错误。
如果您想看看这通常是什么样子,请创建一个新的 Rails 项目并使用脚手架生成器创建一些示例代码。
关于ruby-on-rails - Form_for "First argument in form cannot contain nil or be empty"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15379495/