簡體   English   中英

如何針對特定條件在Rails中批量提取記錄?

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

我正在編寫一個rake任務,以填充“產品”對象記錄。 我目前的邏輯是

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

現在在上面的查詢中,我想獲取從現在開始90天之前創建的記錄。 如何更改以上查詢?

引用

就像是

 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

對於90天后創建的記錄

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

你可以試試:

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

注意:如果您不關心小時和分鍾,可以使用:

Date.today - 90.days 

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM