Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do bulk update in rails on habtm association

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?

like image 826
PrajaktaC Avatar asked Jan 28 '26 22:01

PrajaktaC


1 Answers

There is a method update_all

def update
  users = User.where(id: [325, 326])
  users.update_all group_ids: [1, 2]
end
like image 171
Dan Andreasson Avatar answered Jan 31 '26 12:01

Dan Andreasson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!