我可以使用Rails find_each方法,例如:
User.find_each(:batch_size => 10000) do |user|
------
end
使用find_each方法,有什么方法可以获取数组的索引?喜欢 :
User.find_each(:batch_size => 10000).with_index do |user, index|
------
end
更新:从Rails 4.1.4开始,这是可能的。有关更多信息,请参见此答案。例:
User.find_each(:batch_size => 1000).with_index do |user, index|
user.call_method(index)
end
从方法定义中可以看到,这是不可能的。
def find_each(options = {})
find_in_batches(options) do |records|
records.each { |record| yield record }
end
end
为了完成您想做的事情,您需要创建自己的方法的修改版本
class User
def find_each(options = {})
find_in_batches(options) do |records|
records.each_with_index { |record| yield record, index }
end
end
end
User.find_each(:batch_size => 10000) do |user, index|
------
end
或使用实例变量。
index = 0
User.find_each(:batch_size => 10000) do |user|
# ...
index += 1
end
方法实现没有显示其他默认解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句