简体   繁体   中英

Mass update by ids

In the table about 10,000-20,000 objects. I have about 1000 id entries, which you want to change one value. How to do this correctly? I don't want to use each which will be 1000 times INSERT. I think this is not correct.

PS This is a normal variant?

accounts_closes = Account.where(:alfa_flag => false).pluck(:id)

Account.transaction do
  accounts_closes.each do |account_id|
    Account.connection.execute 'UPDATE accounts SET open = false WHERE id = ' + account_id + ';'
  end
end

You can look at this answer , basically you should use update_all , which constructs single update query for all records of one table. If you need to update only certain records, you can just use where before the update and chain it, like:

Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')

Hope it helps.

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