0

我正在阅读 Rails 指南(http://guides.rubyonrails.org/getting_started.html),并被困在第 11 项“构建多模型表单”中。

这部分练习解释了如何将一个模型的表单字段包含在另一个模型的表单中......

新/编辑帖子上的错误:nil:NilClass 的未定义方法“fields_for”

Extracted source (around line #2):

1: <% @post.tags.build %>
2: <%= form.fields_for :tags do | tag_form | %>
3:   <div class="field">
4:     <%= tag_form.label :name, 'Tag: ' %>
5:     <%= tag_form.text_field :name %>

代码完全按照练习(我什至绝望并直接从示例中复制并粘贴代码)

我的代码发布在下面..我花了几个小时将它与指南中的代码进行比较,它完全一样..谁能指出我可能出了什么问题?

提前谢谢了。

这是我包含部分的代码

模型/post.rb:

class Post < ActiveRecord::Base
  attr_accessible :content, :name, :title, :tags_attributes

  validates :name, :presence =>true
  validates :title, :presence =>true,
                        :length => { :minimum => 5 }
  has_many :comments, :dependent => :destroy
  has_many :tags

  accepts_nested_attributes_for :tags, :allow_destroy => :true,
    :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end

模型/tag.rb:

class Tag < ActiveRecord::Base
  belongs_to :post
  attr_accessible :name
end

帖子/_form.html.erb:

<% @post.tags.build %>
<%= form_for(@post) do |post_form| %>
  <% 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">
    <%= post_form.label :name %><br />
    <%= post_form.text_field :name %>
  </div>
  <div class="field">
    <%= post_form.label :title %><br />
    <%= post_form.text_field :title %>
  </div>
  <div class="field">
    <%= post_form.label :content %><br />
    <%= post_form.text_area :content %>
  </div>
  <h2>Tags</h2>
  <%= render :partial => 'tags/form',
                     :locals => {:from => post_form} %>
  <div class="actions">
    <%= post_form.submit %>
  </div>
<% end %>

标签/_form.html.erb:

<%= form.fields_for :tags do | tag_form | %>
  <div class="field">
    <%= tag_form.label :name, 'Tag: ' %>
    <%= tag_form.text_field :name %>
  </div>
  <% unless tag_form.object.nil?  || tag_form.object.new_record? %>
    <div class="field">
      <%= tag_form.label :_destroy, 'Remove: ' %>
      <%= tag_form.check_box :_destroy %>
    </div>
  <% end %>
<% end %>
4

2 回答 2

2

只是您的帖子/_form 结尾处的一个错字

<%= render :partial => 'tags/form', :locals => {:from => post_form} %>

应该

<%= render :partial => 'tags/form', :locals => {:form => post_form} %>

表格不从!!!

于 2013-02-27T16:23:06.207 回答
0

表格拼写错误。

:locals => {:from => post_form}:locals => {:form => post_form}

于 2013-02-27T16:24:39.257 回答