Rails/Arel:选择所有记录作为 ActiveRecord::Relation

编程入门 行业动态 更新时间:2024-10-27 15:25:00
本文介绍了Rails/Arel:选择所有记录作为 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

本文发布于:2023-10-22 08:08:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1516944.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Arel   Rails   Relation   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!