seand
seand

Reputation: 5296

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?

Upvotes: 7

Views: 1852

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 96934

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.

Upvotes: 14

Related Questions