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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With