Reputation: 14438
How in rails, do you call update_attributes()
on a active record object, and have it create appropriate rows in one-to-many
associated table based on an array param.
Is this possible? Or do I need to manually loop through that param's array and insert the many rows manually via create_record()
etc?
To be clear, I might have users table with 1-to-many addresses. I want to call users.update_attributes() passing in the user details to be updated, but also provide an array of addresses mapping to the addresses table.
Upvotes: 0
Views: 78
Reputation: 7655
In your User
model:
model User
has_many :addresses
accepts_nested_attributes_for :addresses
end
now user can be created with this set of params
params = { user: {
name: 'Dimitri', address_attributes: [
{ country: 'Georgia', city: 'Abasha', line: '35 Kacharava Str.' },
{ country: 'USA', city: 'Los Angeles', line: '10 Infinite Loop' },
{ country: '', _destroy: '1' } # this will be ignored
]
}}
User.create(params[:user])
more details can be found from here.
Upvotes: 2