ruby-on-rails – 在Rails中如何使用find_each方法与索引?
发布时间:2020-12-16 21:43:57 所属栏目:百科 来源:网络整理
导读:我可以使用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 解决方法 从 method definit
我可以使用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 解决方法
从
method definition可以看出,这是不可能的.
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 没有其他默认解决方案,如方法实现所示. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |