I have two models:
#user.rb
has_and_belongs_to_many :groups
#group.rb
has_and_belongs_to_many :users
I want to associate groups to users such that many users can be associated to many groups.
Front end side of the application is sending the user_ids and group_ids to the update method.
So in the UsersController, i've found out each user and associated that user with the groups.
def update
users = User.where(id: [325, 326])
users.each { |user| user.update(group_ids: [1, 2])}
end
I need to know the standard way of updating the associated records and what is the most efficient way of updating associated records?
There is a method update_all
def update
users = User.where(id: [325, 326])
users.update_all group_ids: [1, 2]
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With