0

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.

P.S. 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
  • possible duplicate of [Rails 3 + activerecord, the best way to "mass update" a single field for all the records that meet a condition](http://stackoverflow.com/questions/4912510/rails-3-activerecord-the-best-way-to-mass-update-a-single-field-for-all-the) – Brad Werth Aug 24 '14 at 16:25

1 Answers1

1

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.

Community
  • 1
  • 1
Giron
  • 350
  • 3
  • 16
  • No, your offer for any and all records. And I need to change only some. check p.s. block on question – user3834491 Aug 24 '14 at 16:25
  • That is not quite true, see the links I have posted, I have added an example, so it will be more obvious how to accomplish it. – Giron Aug 24 '14 at 16:26
  • Yes, you're right. I have complicated what could be done easier. Thank you! Account.where(:alfa_flag => false).update_all(open: false) – user3834491 Aug 24 '14 at 16:30