def find_in_batches(options = {})
options.assert_valid_keys(:start, :batch_size)
relation = self
if logger && (arel.orders.present? || arel.taken.present?)
logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
end
start = options.delete(:start)
batch_size = options.delete(:batch_size) || 1000
relation = relation.reorder(batch_order).limit(batch_size)
records = start ? relation.where(table[primary_key].gteq(start)).to_a : relation.to_a
while records.any?
records_size = records.size
primary_key_offset = records.last.id
raise "Primary key not included in the custom select clause" unless primary_key_offset
yield records
break if records_size < batch_size
records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
end
end
可以這樣使用:
Post.find_in_batches(:batch_size => 100, :include => [:user, :category]) do |post|
u = post.user
c = post.category
# do stuff
end
batch_size : 每次撈取的數量.
start : 從哪個 primary_id 開始. (ps: 因為 find_in_batches 是用 id 跟 limit 來 算出 sql 語法的)
範例 : start => 100 Mysql 會變成 select * from table where id >= 100 limt batch_size ;
conditions : 設定其他條件.
官網:http://api.rubyonrails.org/classes/ActiveRecord/Batches.html
沒有留言:
張貼留言