gpt4 book ai didi

ruby-on-rails - accepts_nested_attributes_for 和 nested_form 插件

转载 作者:数据小太阳 更新时间:2023-10-29 08:06:28 25 4
gpt4 key购买 nike

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

对于新 Action 来说效果很好......对于编辑操作,如文档中所述,我必须添加现有关联的 :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 }
# ])

感谢您的帮助。

最佳答案

我发现了我的错误,这是我学到的东西:

当您将 accepts_nested_attributes_for 用于多对多关联时,请保留关联表的 :id 主键。

干杯

关于ruby-on-rails - accepts_nested_attributes_for 和 nested_form 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com