How does Rails ActiveRecord chain "where" clauses without multiple queries?

The where method returns an ActiveRecord::Relation object, and by itself this object does not issue a database query. It's where you use this object that matters.

In the console, you're probably doing this:

@person = Person.where(name: "Jason")

And then blammo it issues a database query and returns what appears to be an array of everyone named Jason. Yay, Active Record!

But then you do something like this:

@person = Person.where(name: "Jason").where(age: 26)

And then that issues another query, but this one's for people who are called Jason who are 26. But it's only issuing one query, so where'd the other query go?


As others have suggested, this is happening because the where method returns a proxy object. It doesn't actually perform a query and return a dataset unless it's asked to do that.

When you run anything in the console, it's going to output the inspected version of the outcome of whatever it is you ran. If you put 1 in the console and hit enter, you'll get 1 back because 1.inspect is 1. Magic! Same goes for "1". A variety of other objects don't have an inspect method defined and so Ruby falls back to the one on Object which returns something ghastly like <Object#23adbf42560>.

Every single ActiveRecord::Relation object has the inspect method defined on it so that it causes a query. When you write the query in your console, IRB will call inspect on the return value from that query and output something almost human readable, like the Array that you'd see.


If you were just issuing this in a standard Ruby script, then no query would be executed until the object was inspected (via inspect) or was iterated through using each, or had the to_a method called on it.

Up until one of those three things happen, you can chain as many where statements on it as you will like and then when you do call inspect, to_a or each on it, then it will finally execute that query.


There are a number of methods that are known as "kickers" that actually fire off the query to the database. Prior to that, they just create AST nodes, which once kicked, will generate the actual SQL (or language being compiled to) and run the query.

See this blog post for a deeper explanation of how this is done.


You can read the code, but one concept here is the proxy pattern.

Probably @person is not the real object but a proxy to this object and when you need some attribute there the active record finally execute the query. Hibernate has the same concept.