sql – Rails:使用AREL进行批量属性查询
发布时间:2020-05-24 15:09:25 所属栏目:MsSql 来源:互联网
导读:我想使用像find_in_batches这样的东西,但是我不想对完全实例化的AR对象进行分组,而是将某个属性组合起来,比如说,就像id一样.所以,基本上,使用find_in_batches和pluck的混合: Cars.where(:engine = Turbo).pluck(:id).find_in_batches do |ids| puts idsend#
|
我想使用像find_in_batches这样的东西,但是我不想对完全实例化的AR对象进行分组,而是将某个属性组合起来,比如说,就像id一样.所以,基本上,使用find_in_batches和pluck的混合: Cars.where(:engine => "Turbo").pluck(:id).find_in_batches do |ids| puts ids end # [1,2,3....] # ... 有没有办法做到这一点(也许与Arel),而不必自己编写OFFSET / LIMIT逻辑或重复分页宝石如paginate或kaminari? 解决方法这不是理想的解决方案,但是这里的方法只是复制粘贴大多数find_in_batches但产生关系而不是记录数组(未经测试) – 只需将其修补为关系: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计算),但是你得到了精神. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
