ActiveRecord find_each combined with limit and order

后端 未结 13 2082
温柔的废话
温柔的废话 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:36

    I was looking for the same behaviour and thought up of this solution. This DOES NOT order by created_at but I thought I would post anyways.

    max_records_to_retrieve = 50000
    last_index = Thing.count
    start_index = [(last_index - max_records_to_retrieve), 0].max
    Thing.active.find_each(:start => start_index) do |u|
        # do stuff
    end
    

    Drawbacks of this approach: - You need 2 queries (first one should be fast) - This guarantees a max of 50K records but if ids are skipped you will get less.

提交回复
热议问题