简体   繁体   中英

rails field_for associated model tags with error “undefined method `model_name' for Array:Class'”

according to http://guides.rubyonrails.org/getting_started.html , I have below relationship models,

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

normally below code could work well when I sent a edit request,these existing tags are listed as editable elements on the page.

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

but now,refer to below instance code on 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 %>

then I change the statement with fields_for to below format, why it always always prompt undefined method `model_name' for Array:Class

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

at last, I make it work with below update

<% @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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM