我在_form.html.haml部分中有以下代碼,它用於新建和編輯操作。 (FYI我使用Ryan Bates的插件nested_form)accept_nested_attributes_for和nested_form插件
.fields
- f.fields_for :transportations do |builder|
= builder.collection_select :person_id, @people, :id, :name, {:multiple => true}
= builder.link_to_remove 'effacer'
= f.link_to_add "ajouter", :transportations
正常工作新動作...... 的編輯操作,如DOC解釋,我已經添加的:已經ID現有的協會,所以,我必須添加像
= builder.hidden_field :id, ?the value? if ?.new_record?
我怎樣才能得到的價值?
這裏是accepts_nested_attributes_for作參考文檔(來源:http://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb#L332)
# Assigns the given attributes to the collection association.
#
# Hashes with an <tt>:id</tt> value matching an existing associated record
# will update that record. Hashes without an <tt>:id</tt> value will build
# a new record for the association. Hashes with a matching <tt>:id</tt>
# value and a <tt>:_destroy</tt> key set to a truthy value will mark the
# matched record for destruction.
#
# For example:
#
# assign_nested_attributes_for_collection_association(:people, {
# '1' => { :id => '1', :name => 'Peter' },
# '2' => { :name => 'John' },
# '3' => { :id => '2', :_destroy => true }
# })
#
# Will update the name of the Person with ID 1, build a new associated
# person with the name `John', and mark the associatied Person with ID 2
# for destruction.
#
# Also accepts an Array of attribute hashes:
#
# assign_nested_attributes_for_collection_association(:people, [
# { :id => '1', :name => 'Peter' },
# { :name => 'John' },
# { :id => '2', :_destroy => true }
# ])
感謝您的幫助。
你說什麼「保留:關聯表的主鍵」是什麼意思?由於rails文檔只提到1對n和1對1關聯http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for,我不知道如何用n對n來實現這一點。 – v4r 2012-06-27 18:17:54