简体   繁体   中英

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

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM