the12
the12

Reputation: 2415

How does Rails know to return all records even when it is not specfied with the method .all?

I was just playing around with ActiveRecord. While doing so, I noticed something unusual that if I type two separate queries, one with .all and the other one without. all, that the SQL query would return in both cases, all the records from the model:

User.includes(:cart) vs. User.includes(:cart).all vs. User.all.includes(:cart)

also,

User.all vs. User.order(:username)

(With exception to the fact that the second query is ordered, they both yield the same result. They both return all the queries.)

They both seem to be yielding the same result. How does Rails know to capture all the records, even when it is not explicitly stated with .all?

Upvotes: 0

Views: 53

Answers (1)

Aaron Breckenridge
Aaron Breckenridge

Reputation: 1819

ActiveRecord cleverly delays performing a query until the results are needed.

In a REPL (Read-Eval-Print-Loop) like the Rails console, these ActiveRecord queries are automatically inspected (cast so they can be rendered on the console), which will execute the query so the results can be rendered.

Note that you'll still get back objects representing the query until it's cast to an Array.

User.all.class #=> User::ActiveRecord_Relation
User.where('1 = 1').class #=> User::ActiveRecord_Relation
User.all.to_a #=> Array

This became the norm way back in Rails 3.

Upvotes: 1

Related Questions