Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 706
Jeriko Avatar asked Apr 08 '11 13:04

Jeriko


People also ask

What is ActiveRecord relation?

Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet). Once you run that query by calling to_a , each , first etc. on that Relation a single instance or an array of ActiveRecord::Base instances will be returned.

What is Arel in ActiveRecord?

Arel is a SQL abstraction that ActiveRecord uses to build SQL queries. Arel wraps each component of the SQL query language with Ruby objects and provides an expressive DSL for composing SQL queries. When using Arel, you're mainly interacting with tables ( Arel::Table ) and nodes ( Arel::Nodes::Node subclasses).

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is Arel SQL Rails?

Arel is a powerful SQL AST manager that lets us appropriately combine selection statements for simple to very complicated queries. However, reader be cautioned – Arel is still a private API provided by Rails. Meaning that future versions of Rails could be subject to changes in Arel.


2 Answers

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

like image 199
Dylan Markow Avatar answered Oct 30 '22 13:10

Dylan Markow


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

like image 12
Kyle Heironimus Avatar answered Oct 30 '22 15:10

Kyle Heironimus