ruby-on-railsruby-on-rails-6has-many

What is the best way to update a has_many association when creating, updating and removing in the same request using Rails?


I am looking to update a has_many relationship. The data being received from the request may have data to be created, some data may need updating to new values and some data may no longer be in the array but is still in the database that would need to be removed.

In theory you could delete them all out and re-create everything or loop through each array for differences but is there a better/ recommended practice for this?


Solution

  • You can define accepts_nested_attributes_for for the associated model like below:

    class Library
      has_many :books
    
      accepts_nested_attributes_for :books
    end
    

    and then wherever you need to update the associated has_many objects, you can pass the objects as an array. Example:

    books = [
      { name: 'New book' },
      { id: 10, name: 'A new name' }
      { id: 11, _destroy: true }
    ]
    

    suppose you want to do it for library_object instance:

    library_object.update(books_attributes: books)
    

    This will Create a new book object with name New book, Update the name of book object with id 10 to A new name and Delete the book object with id 11.