Reputation: 2672
I have
class Test < ActiveRecord::Base
has_many :samples
accepts_nested_attributes_for :samples
end
and
class Sample < ActiveRecord::Base
belongs_to :tests
end
Now when i create new value as follows
curl -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST
http://localhost:3000/tests.json
-d "{\"test\":{\"name\":\"xxxxxx\", \"samples_attributes\":[{\"username\":\"yyyyyyy\",\"age\":\"25\"}]}}"
it creates a new value for the test and it also creates an entry in the sample
table but when updating it updates the test table whereas it creates a new entry in the sample table. so how can i make it to update the present entry?
please help me.
Upvotes: 2
Views: 3109
Reputation: 151
You need to pass the id
in the hash for update records (view API):
class Member < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts
end
If the hash contains an id
key that matches an already associated record, the matching record will be modified:
member.attributes = {
name: 'Joe',
posts_attributes: [
{ id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
{ id: 2, title: '[UPDATED] other post' }
]
}
For each hash that does not have an id
key a new record will be instantiated.
params = { member: {
name: 'joe', posts_attributes: [
{ title: 'Kari, the awesome Ruby documentation browser!' },
{ title: 'The egalitarian assumption of the modern citizen' }
]
}}
Upvotes: 8