Anderson Pierok
Anderson Pierok

Reputation: 337

Nested_attributes rails not found with two nested's

I have a problem, I am saving an object with 2 nested_attributes, but it is saving only the second nested_attributes, if I back and update the first nested_attributes, it saves correctly. An attribute has has_many and another has_one, it is saving just one at a time.

ex:

class Author
   has_many :books
   has_one :address

   accepts_nested_attributes_for :books
   accepts_nested_attributes_for :address

end

Params:
author: {books_attributes: {"0" => {title: "Title Test", id: 1}}, address_attributes: {city: "São Paulo", id: 2}}

This example saving only the author's books

How can I solve this?

Upvotes: 1

Views: 70

Answers (1)

Bruno Mucelini Mergen
Bruno Mucelini Mergen

Reputation: 301

I had this same problem, I couldn't resolve with a good way. I don't know why, but before save, it seems that the attributes of the address are being lost. I did this:

class Author    
     has_many :books    
     has_one :address
     accepts_nested_attributes_for :books   
     accepts_nested_attributes_for :address

     before_save :build_address_object
     after_save  :save_address_object!

     private

     def build_address_object
        @address = address
     end

     def save_address_object!
         return unless @address
         @address.author = self
         @address.save
     end
end

Note that the book validates the attributes of the address but when will save the address, it seems he loses parameters.

Upvotes: 2

Related Questions