gpt4 book ai didi

sql - rails : batched attribute queries using AREL

转载 作者:行者123 更新时间:2023-12-04 08:49:35 25 4
gpt4 key购买 nike

我想使用类似 find_in_batches 的东西,但不是对完全实例化的 AR 对象进行分组,我想对某个属性进行分组,例如 id。所以,基本上,混合使用 find_in_batchespluck :

Cars.where(:engine => "Turbo").pluck(:id).find_in_batches do |ids|
puts ids
end

# [1, 2, 3....]
# ...

有没有办法做到这一点(也许用 Arel),而不必自己编写 OFFSET/LIMIT 逻辑或重复分页 gems 像 will paginate 或 kaminari?

最佳答案

这不是理想的解决方案,但这里有一种方法只是复制粘贴 find_in_batches 的大部分内容。但产生一个关系而不是一组记录(未经测试) - 只需将其修补成 Relation :

def in_batches( options = {} )
relation = self

unless arel.orders.blank? && arel.taken.blank?
ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
end

if (finder_options = options.except(:start, :batch_size)).present?
raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order].present?
raise "You can't specify a limit, it's forced to be the batch_size" if options[:limit].present?

relation = apply_finder_options(finder_options)
end

start = options.delete(:start)
batch_size = options.delete(:batch_size) || 1000

relation = relation.reorder(batch_order).limit(batch_size)
relation = start ? relation.where(table[primary_key].gteq(start)) : relation

while ( size = relation.size ) > 0

yield relation

break if size < batch_size

primary_key_offset = relation.last.id
if primary_key_offset
relation = relation.where(table[primary_key].gt(primary_key_offset))
else
raise "Primary key not included in the custom select clause"
end
end
end

有了这个,你应该能够做到:
Cars.where(:engine => "Turbo").in_batches do |relation|
relation.pluck(:id)
end

这可能不是最好的实现(特别是关于primary_key_offset 计算,它实例化一个记录),但你明白了。

关于sql - rails : batched attribute queries using AREL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com