How can I run updates in batches in Rails 3/4?

后端 未结 6 1069
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 01:09

I need to mass-update many thousands of records, and I would like to process the updates in batches. First, I tried:

Foo.where(bar: \'bar\').find_in_batches.upda         


        
6条回答
  •  伪装坚强ぢ
    2021-02-05 02:13

    pdobb's answer is on the right track, but didn't work for me in Rails 3.2.21 because of this issue of ActiveRecord not parsing OFFSET with UPDATE calls:

    https://github.com/rails/rails/issues/10849

    I modified the code accordingly and it worked fine for concurrently setting the default value on my Postgres table:

    batch_size = 1000
    0.step(Foo.count, batch_size).each do |offset|
      Foo.where('id > ? AND id <= ?', offset, offset + batch_size).
          order(:id).
          update_all(foo: 'bar')
    end
    

提交回复
热议问题