Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 ActiveRecord method chaining, under the hood

Let's say you build a query involving multiple method chaining, such as

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

I'm wondering what happens behind the scene? Presumably each part of the chain will help build a SQL SELECT and once the chain is 'complete' the statement is executed, models created etc. How does it 'know' where the end of the chain is? Does each method return an ActiveRecord::Relation which creates a SQL fragment?

like image 703
seand Avatar asked Feb 29 '12 05:02

seand


1 Answers

You are correct, each of these returns an ActiveRecord::Relation. Each method call builds upon the relation it was called on (except the first, which obviously has nothing to build on, as it was not called on a relation), and returns that.

It "knows" where the end of the chain is because the query is not actually executed till you try and manipulate/access the data, and in doing so have (usually implicitly) called to_a which runs exec_queries.

like image 196
Andrew Marshall Avatar answered Sep 21 '22 15:09

Andrew Marshall