Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Update Nested Attributes

Updating Nested Attributes append instead of updating in has many relationships I am trying to use Rails 4 Update_attributes

Class Person <ActiveRecord::Base  has_many :pets  accepts_nested_attributes_for :pets end  Class Pet < ActiveRecord::Base  belongs_to :person end 

In my controller I am recieveing the params as {id: 23, house_no:'22A', pets: [{name:'jeffy', type:'dog'}, {name:'sharky', type:'fish'}]}

and my update method is

def update   @Person = Person.find(params[:id])   if @Person.update(person_params)     @Person.save     render 'persons/create', status 200   else     render 'persons/create', status 400   end end  private def person_params   person_params = params.permit(:house_no)   person_params.merge! ({pets_attributes: params[:pets]}) if params[:pets].present?   person_params end 

Now when I update it and if the person already has a pet then the new pets gets appended instead of getting updated eg if a person with id 1 has 1 pet named "Tiger" and I update that person with 2 pets named "Shasha" and "Monti" then the person record has 3 pets (Tiger, Shasha and Monti) instead of updating it to 2 (Shasha and Monti)

like image 963
Kush Jain Avatar asked May 06 '14 11:05

Kush Jain


Video Answer


2 Answers

You have to add the :id attribute to the :pets_attributes array in person_params.

You need to permit the id attribute to update the records.

like image 75
Panos Malliakoudis Avatar answered Oct 05 '22 11:10

Panos Malliakoudis


see the manual:

http://api.rubyonrails.org/v4.0.1/classes/ActiveRecord/NestedAttributes/ClassMethods.html

you need to send in your attributes like pets_attributes:[{name:'jeffy', type:'dog'}, {name:'sharky', type:'fish'}]

and it should work fine.

Please read

You can now set or update attributes on the associated posts through an attribute hash for a member: include the key :posts_attributes with an array of hashes of post attributes as a value.For each hash that does not have an id key a new record will be instantiated, unless the hash also contains a _destroy key that evaluates to true.

like image 40
Suchit Puri Avatar answered Oct 05 '22 12:10

Suchit Puri