简体   繁体   中英

Rails/Arel: Selecting all records as an ActiveRecord::Relation

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?

Try relation = Model.scoped . That will give you the relation instead of the actual results.

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

You would want:

relation = Model.scoped

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:

Anonymous scopes tend to be useful when procedurally generating complex queries, where passing intermediate values (scopes) around as first-class objects is convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM