我在_form.html.haml部分中有以下代码,它用于新建和编辑操作。 (我使用Ryan Bates的插件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
适用于新动作...... 对于编辑操作,如文档中的解释,我要添加:已存在关联的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 }
# ])
感谢您的帮助。
答案 0 :(得分:1)
我发现了我的错误,这是我学到的事情:
当您对多个关联使用accepts_nested_attributes_for时,请保留关联表的:id主键。
干杯
答案 1 :(得分:1)
当使用“:_delete”而不是“:_destroy”时,我的工作正常。我在轨道上2.3.4。 Ruby 1.8.7
看看这个:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605
答案 2 :(得分:0)
Rails正式支持嵌套表单。您正在做的事情(特别是使用fields_for方法)可能与RAils渲染fields_for的内置方式相冲突。
以下是Rails方法做field_for的文档......它非常彻底:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605
我强烈建议您尝试使用内置方式而不是插件,因为这种方式几乎可以无限期地得到支持。
希望这有帮助!