Gareth Burrows
Gareth Burrows

Reputation: 1182

ruby iterate through sql results

I need to iterate through records found with sql and update them all.

I need to update a couple of thousand records and the requirements are complex enough that I search for the records by SQL. The code below works but is there a way of doing it without performing several thousand update statements?

users = User.find_by_sql "select e.id from users e inner join accounts a on a.id = e.account_id where e.account_id not in (1955,3083, 3869)"
users.each do |user|
  u = User.find(user.id)
  if u
    u.update_attribute(:last_name, 'X')
  end
end

Upvotes: 1

Views: 227

Answers (1)

Jordan Running
Jordan Running

Reputation: 106147

This would do the same thing as your code, but with a single UPDATE:

User.joins(:accounts)
  .where("users.account_id NOT IN (?)", [1955, 3083, 3869])
  .update_all(last_name: "X")

You can find the documentation for update_all here.

Upvotes: 2

Related Questions