我对Rails3非常陌生,并且我已经学习了一些教程,现在我正在尝试“使用”所创建的代码。我遵循了来自http://guides.rubyonrails.org/getting_started.html的教程
我正在尝试使用以下代码在主页上呈现新帖子的表单:
<%= render :partial => "posts/form" %>posts/_form.html.erb如下所示:
<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>下面是我得到的错误:
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for(@post) do |f| %>
2: <% if @post.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
Trace of template inclusion: app/views/home/index.html.erb
Rails.root: d:/server/cazare
Application Trace | Framework Trace | Full Trace
app/views/posts/_form.html.erb:1:in `_app_views_posts__form_html_erb___794893824_70478136_519766'
app/views/home/index.html.erb:5:in `_app_views_home_index_html_erb__967672939_70487520_0'我知道这对你们中的一些人来说可能是小菜一碟,但我正在尝试理解Rails上的一切工作原理,所以我希望你们能理解我。
提前感谢!
发布于 2011-04-07 16:31:29
@post变量未在控制器中实例化:)
因此,控制器操作中的"@post = Post.new"应该可以做到这一点
发布于 2011-04-07 16:30:54
Rails正在尝试为对象@post构建表单。为此,它需要知道@post是什么类型的对象;这样,它就可以找到对象中的任何现有数据,并将其填充到表单中。Rails将一个名为model_name的方法移植到对象上进行查找,但它不会移植到NilClass ( nil对象的类)上。
我怀疑您还没有在任何地方定义@post -它是控制器的一个实例变量,所以您可能希望控制器从数据库中找到@post,或者调用@post = Post.new -所以它是nil。
发布于 2012-11-29 17:08:04
在post/_form.html.erb中,
变化
<%= form_for(@post) do |f| %>至
<%= form_for(Post.new) do |f| %>https://stackoverflow.com/questions/5577928
复制相似问题