Simon Ninon
Simon Ninon

Reputation: 2441

ActiveRecord, method chaining and request execution

I'm currently trying to understand how does ActiveRecord work to chain the conditions methods and then execute the sql request.

Understanding methods chaining is pretty easy and everything I thought is nicely explained and resumed here here.

However, there is something I still can't figure out and that the above article does not explain: how does ActiveRecord know when to execute the SQL request.

For example, if I code User.where(some_column: "hello").limit(5), ActiveRecord will instantiate a query builder, set the conditions about the some_column value and the limited number of results.

But, after executing the .limit(5), it also executes the request and returns the result: how can ActiveRecord know? How can it know that it is the final condition method and that it needs to return a result? Does it execute an SQL request at each chained condition?

In the article I've posted above, the author was tricking by calling a final method, each which was executing the request and returning the result.

Upvotes: 4

Views: 1185

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176352

limit(5) is not more special than where, in fact it returns an ActiveRecord::Relation like where does. You can swap the order of the chain to prove it.

User.where(some_column: "hello").limit(5)
User.limit(5).where(some_column: "hello")

What happens is that there are certain methods that called explicitly (for example in the controller) or implicitly (in the CLI) triggers the execution of the query. These methods are for example:

  • Enumerable methods such as each, select, etc
  • Explicit casting methods such as to_a
  • Query methods such as first, last, take

Whenever one of these methods is called implicitly or explicitly then the query is executed.

Upvotes: 5

Related Questions