-->

Rails/Arel: Selecting all records as an ActiveReco

2019-02-02 03:16发布

问题:

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?

回答1:

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



回答2:

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



回答3:

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.