ActiveRecord find_each combined with limit and order

后端 未结 13 2085
温柔的废话
温柔的废话 2020-12-02 11:41

I\'m trying to run a query of about 50,000 records using ActiveRecord\'s find_each method, but it seems to be ignoring my other parameters like so:



        
相关标签:
13条回答
  • 2020-12-02 12:45

    You can iterate backwards by standard ruby iterators:

    Thing.last.id.step(0,-1000) do |i|
      Thing.where(id: (i-1000+1)..i).order('id DESC').each do |thing|
        #...
      end
    end
    

    Note: +1 is because BETWEEN which will be in query includes both bounds but we need include only one.

    Sure, with this approach there could be fetched less than 1000 records in batch because some of them are deleted already but this is ok in my case.

    0 讨论(0)
提交回复
热议问题