PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

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

 October 21, 2022     has-many, ruby-on-rails, ruby-on-rails-6     No comments   

Issue

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.



Answered By - Sachin Singh
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing