简体   繁体   English

红宝石遍历SQL结果

[英]ruby iterate through sql results

I need to iterate through records found with sql and update them all. 我需要遍历使用sql找到的记录并更新所有记录。

I need to update a couple of thousand records and the requirements are complex enough that I search for the records by SQL. 我需要更新几千条记录,而且要求非常复杂,以至于我无法通过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 : 这将与您的代码执行相同的操作,但是只有一个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 . 您可以在此处找到update_all的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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