Accepts_nested_attributes_for and nested_form plugin

I have the following code in partial format _form.html.haml, which is used for new actions and editing actions. (fyi I am using the Ryan Bates nested_form plugin )

.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

works fine for a new action ... for an editing action, as the document explains, I have to add: id of already existing associations, so I have to add something like

= builder.hidden_field :id, ?the value? if ?.new_record?

How can I get the value?

Here is the accepts_nested_attributes_for document for reference (source: 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 }
# ])

Thank you for your help.

+3
3

, fyi:

accepts_nested_attributes_for - , : id .

+1
+1

Rails. , ( , fields_for), RAils fields_for.

Rails fields_for... :

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605

I highly recommend that you try the built-in method instead of the plugin, as this will be supported almost endlessly.

Hope this helps!

0
source

Source: https://habr.com/ru/post/1731458/


All Articles