Rails 4 相当于 Rails 3 'Model.all' [英] Rails 4 equivalent of Rails 3 'Model.all'
问题描述
在 Rails 3 中,如果我想点击 db,我会在查询结束时使用 .all.这在我执行诸如在写入时刷新缓存之类的操作时很有用(因此读取总是命中缓存).
In Rails 3 if I wanted to hit the db I'd take .all on the end of a query. This is useful for when I'm doing things like refreshing cache on writes (so reads always hit cache).
现在在 Rails 4 中,Model.all 返回一个 ActiveRecord::Relation
对象(即不命中数据库).让它实际转到数据库并返回指定记录的最佳方法是什么?
Now in Rails 4, Model.all returns an ActiveRecord::Relation
object (ie doesn't hit the db). What is the best way to get it actually go to the db and return the records specified?
推荐答案
Model.all.to_a
在 Rails 4 中将给出与 Rails 中的 Modal.all
相同的结果3.
Model.all.to_a
in Rails 4 will give the same result as Modal.all
in Rails 3.
修改:
@Bigxiang,在他的评论中指出尝试Model.all.load
,这个方法肯定命中了数据库,但仍然返回一个ActiveRecordRelation.基本上要从Rails 3"中获得与 Model.all
类似的功能,您可以在返回的 ActiveRecordRelation
上调用 to_a
.
@Bigxiang, pointed out in his comment to try Model.all.load
, this method for certain hits the database but still returns an ActiveRecordRelation. And basically to get a similar functionality as Model.all
from "Rails 3", you can call to_a
on the returned ActiveRecordRelation
.
这篇关于Rails 4 相当于 Rails 3 'Model.all'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!