Rails/Arel:选择所有记录作为 ActiveRecord::Relation [英] Rails/Arel: Selecting all records as an ActiveRecord::Relation
问题描述
在 Rails 中使用 Arel - 我正在寻找一种创建 ActiveRecord::Relation
的方法,它可以有效地生成 SELECT * FROM table
,我仍然可以操纵它进一步.
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
}
这很好用,并且具有向 MySQL 发送 COUNT
查询的优点,而不是实际选择记录本身.
This works fine, and has the advantage of firing off COUNT
queries to MySQL, rather than actually selecting the records themselves.
但是,我现在需要在计数中包含存档记录,但是 relation = Model.all
会生成一个 Array
,我正在寻找一个 ActiveRecord::Relation
.
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(nil))
,它有效,但似乎有点荒谬.
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
返回一个关系(以前没有)
For Rails 4.1 and above: Model.all
returns a relation (where it previously did not)
对于 Rails 4.0:Model.where(nil)
For Rails 4.0: Model.where(nil)
对于 Rails 3.x:Model.scoped
For Rails 3.x: Model.scoped
这篇关于Rails/Arel:选择所有记录作为 ActiveRecord::Relation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!