How to fetch records in batches in rails for a specific condition?

2.9k Views Asked by At

I am writing a rake task, to populate a "Product" object records. my current logic is

namespace :populate_product do
    desc "This task is to populate product object, with product ID"
        task populate_coaching_product_id: :environment do
        UserProduct.find_each(batch_size: 10_000) do |user_product|
          user_product.save
        end
    end
end

Now in the above query, I want to fetch records which are created 90 days back, from now. How can I change the above query?

2

There are 2 best solutions below

0
Salil On

Ref this

Something like

 Person.where("age > 21").find_in_batches do |group|
   sleep(50) # Make sure it doesn't get too crowded in there!
   group.each { |person| person.party_all_night! }
 end

For the records which are created 90 days back use

UserProduct.where('created_at <= ?', Time.now - 90.days ).find_each(batch_size: 10000) do |user_product|
  user_product.save
end
2
hoangdd On

You can try:

UserProduct.where('created_at >= ?', Time.now - 90.days ).find_each(batch_size: 10_000) do |user_product|
  user_product.save
end

Note: If you don't care about hour & minute, you can use:

Date.today - 90.days 

Hope this helps.