find_each
是 ActiveRecord 4.0.0 版中 ActiveRecord 函数 all
的可接受替代品吗?
例如,之前我有:
all_users = User.all
它会产生一条警告,说明 ActiveRelation:all 已被弃用。
作为替代,我想到了:
User.find_each do |user|
all_users += user
end
这是可以接受的,还是我应该换一种方式?
我理解使用 find_each
的原因是因为“批处理”将允许查询在有非常大的数据集时停止运行。对于这种情况,我们假设数据集很小。
编辑
似乎只有在使用条件时才会出现弃用错误,例如:
User.all(:conditions => ["name like ?", "%bob%"])
产生:
DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a rel ation, you can call #load (e.g.
Post.where(published: true).load
). If you want to get an array of records from a relation, you can call #to_a (e.g.Post.wher e(published: true).to_a
). (called from irb_binding at (irb):8)
上面的正确替换似乎是:
User.where("name like ?", "%bob%")
最佳答案
Model.all
在 Rails 4 中没有弃用,但它已经改变了。它不是返回所有记录的数组,而是返回一个速度明显更快的 ActiveRecord 关系。
Model.all
旨在弃用以前延迟加载记录的 Model.scoped
。 Model.all
现在可用于更轻松地链接方法,而不是 scoped
。
您可以在 article 中阅读所有相关信息.
关于ruby - 导轨 4 : alternative for ActiveRecord 'all' as it is now deprecated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528383/