rails field_for关联的模型标记,错误“未定义的方法`model_name'对于Array:Class'”

时间:2013-06-13 13:39:37

标签: ruby-on-rails ruby-on-rails-3

根据http://guides.rubyonrails.org/getting_started.html,我有以下关系模型,

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


class Post < ActiveRecord::Base
  attr_accessible :context, :title, :tags_attributes

  validates :title, :presence => true
  validates :context, :presence => true, :length => {:minimum => 5}

  has_many :comments
  has_many :tags

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

通常在我发送编辑请求时代码下方可以正常工作,这些现有代码会在页面上列为可编辑元素。

<%= form_for(@post) do |post_form| %>

  <%= post_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 %>

但现在,请参阅以下http://guides.rubyonrails.org/form_helpers.html

上的实例代码
<%= form_for @person, :url => { :action => "create" } do |person_form| %>
  <%= person_form.text_field :name %>
  <%= fields_for @person.contact_detail do |contact_details_form| %>
    <%= contact_details_form.text_field :phone_number %>
  <% end %>
<% end %>

然后我将使用fields_for的语句更改为以下格式,为什么它总是提示 数组的未定义方法`model_name':Class

<%= fields_for @post.tags do |tag_form|%>

1 个答案:

答案 0 :(得分:1)

最后,我使用以下更新

<% @post.tags.each do |tag| %>
  <%= post_form.fields_for tags,tag 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 %>
<% end %>