ActiveRecord find_each combined with limit and order

后端 未结 13 2131
温柔的废话
温柔的废话 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条回答
  •  猫巷女王i
    2020-12-02 12:44

    I had the same problem with a query with DISTINCT ON where you need an ORDER BY with that field, so this is my approach with Postgres:

    def filtered_model_ids
      Model.joins(:father_model)
           .select('DISTINCT ON (model.field) model.id')
           .order(:field)
           .map(&:id)
    end
    
    def processor
      filtered_model_ids.each_slice(BATCH_SIZE).lazy.each do |batch|
        Model.find(batch).each do |record|
          # Code
        end
      end
    end
    

提交回复
热议问题