accepts_nested_attributes_for and nested_form plugin

Posted by Denis on Stack Overflow See other posts from Stack Overflow or by Denis
Published on 2010-02-04T20:20:43Z Indexed on 2010/05/07 0:48 UTC
Read the original article Hit count: 419

Filed under:
|
|

Hi folks,

I've the following code in a _form.html.haml partial, it's used for new and edit actions. (fyi I use the Ryan Bates' plugin 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

works fine for the new action... for the edit action, as explain in the doc, I've to add the :id of already existing associations, so, I've to add something like

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

How can I get the value?

Here is the doc of accepts_nested_attributes_for 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 }
# ])

Thanks for your help.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails