简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM