我在_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 }
# ])谢谢你的帮助。
发布于 2010-02-07 10:45:04
我发现了我的错误,以下是我学到的仅供参考:
当您使用具有多对多关联的accepts_nested_attributes_for时,请保留关联表的:id主键。
干杯
发布于 2010-05-07 08:41:13
当使用":_delete“而不是":_destroy”时,我的方法有效。我使用的是rails 2.3.4。Ruby 1.8.7
看看这个:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605
发布于 2010-02-05 09:08:20
Rails正式支持嵌套表单。您正在做的事情(特别是使用fields_for方法)可能与RAils内置的呈现fields_for的方式冲突。
下面是Rails方法的文档,用来做field_ for……非常详细:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605
我强烈建议你尝试内置的方式,而不是插件,因为它将继续得到几乎无限期的支持。
希望这能有所帮助!
https://stackoverflow.com/questions/2202882
复制相似问题