Rails 3 ActiveRecord method chain under the hood

Suppose you create a query that includes a multiple chain of methods, for example

Post.where('id > 10').limit(20).order('id asc').except(:order) 

I wonder what happens behind the scenes? Presumably, each part of the chain will help to build an SQL SELECT, and as soon as the chain is “completed”, the statement is executed, the created models, etc. How does he “know” where the end of the chain is? Each method returns ActiveRecord :: Relation, which creates the SQL fragment?

+7
source share
1 answer

You are right, each of them returns ActiveRecord::Relation . Each method call is built on the relation on which it was called (with the exception of the first, which, obviously, has nothing to build on, since it was not called on the relation) and returns this.

He “knows” where the end of the chain is that the request is not actually executed until you try to manipulate / access the data, and (usually implicitly) is called to_a , which runs exec_queries .

+13
source

All Articles