Rails/Arel:选择所有记录作为 ActiveRecord::Relation
在 Rails 中使用 Arel - 我正在寻找一种创建 ActiveRecord::Relation
的方法,该方法可以有效地生成 SELECT * FROM table
,我仍然可以进一步操作它。
例如,我有一个分为多个类别的模型,我通过以下方式返回这些类别的计数:
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
查询的优点,而不是实际上自己选择记录。
但是,我现在需要在计数中包含存档记录,但 relation = Model.all
会生成 Array
,并且我正在寻找 ActiveRecord: :关系
。
我能想到的唯一方法是 model.where(model.arel_table[:id].not_eq(nil)) ,它有效,但似乎有点荒谬。
任何人都可以阐明这一点吗?
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
}
This works fine, and has the advantage of firing off COUNT
queries to MySQL, rather than actually selecting the records themselves.
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
.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
relation = Model.scoped
。这将为您提供关系而不是实际结果。Try
relation = Model.scoped
. That will give you the relation instead of the actual results.对于 Rails 4.1 及更高版本:
Model.all
返回一个关系(以前没有)对于 Rails 4.0:
Model.where(nil)
对于 Rails 3.x:<代码>模型.范围
For Rails 4.1 and above:
Model.all
returns a relation (where it previously did not)For Rails 4.0:
Model.where(nil)
For Rails 3.x:
Model.scoped
您可能会想要:
如果您看到关系是什么,它实际上是一个
ActiveRecord::Relation
。正如您可以从此页面看到:
http://api .rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html#method-i-scoped
它表示以下内容:
You would want:
which if you see what relation is, it is in fact an
ActiveRecord::Relation
.As you can see from this page:
http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html#method-i-scoped
It says the following: