轨道/阿雷尔:选择所有记录作为一个ActiveRecord ::关系 [英] Rails/Arel: Selecting all records as an ActiveRecord::Relation
问题描述
使用阿雷尔Rails中 - 我正在寻找创建的ActiveRecord ::关联
,有效地导致了 SELECT * FROM表的方式
,我可以进一步处理。
Using Arel in Rails - I'm looking for a way of creating an ActiveRecord::Relation
that effectively results in SELECT * FROM table
, which I can still manipulate further.
例如,我有一个模型,该模型分成多个类别,我在下面的方式返回计数这些:
For example, I have a model that's split up into multiple categories, and I return counts for these in the following manner:
relation = Model.where(:archived => false) # all non-archived records
record_counts = {
:total => relation.count,
:for_sale => relation.where(:for_sale => true).count
:on_auction => relation.where(:on_auction => true).count
}
这工作得很好,并具有发射了 COUNT
查询到MySQL,而不是实际选择记录本身的优势。
This works fine, and has the advantage of firing off COUNT
queries to MySQL, rather than actually selecting the records themselves.
不过,我现在需要包括在计数存档记录,但关系= Model.all
导致一个阵列
,我正在寻找一个的ActiveRecord ::关联
。
However, I now need to include archived records in the counts, but relation = Model.all
results in an Array
, and I'm looking for an ActiveRecord::Relation
.
我能想到这样做的唯一方法是 model.where(model.arel_table [:ID] .not_eq(无))
,它的工作原理,但略微显得荒谬的。
The only way I can think of doing this is model.where(model.arel_table[:id].not_eq(nil))
, which works, but seems slightly absurd.
任何人都可以阐明这个任何光线?
Can anyone shed any light on this?
推荐答案
有关Rails的4.1及以上版本: Model.all
返回的关系(它previously做没有)
For Rails 4.1 and above: Model.all
returns a relation (where it previously did not)
有关Rails的4.0: Model.where(无)
For Rails 4.0: Model.where(nil)
有关的Rails 3.x的: Model.scoped
For Rails 3.x: Model.scoped
这篇关于轨道/阿雷尔:选择所有记录作为一个ActiveRecord ::关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!