我在_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