title: ActiveRecord, method chaining and request execution
body: <p>I'm currently trying to understand how does ActiveRecord work to chain the conditions methods and then execute the sql request.</p>
  
  <p>Understanding methods chaining is pretty easy and everything I thought is nicely explained and resumed here <a href="http://jeffkreeftmeijer.com/2011/method-chaining-and-lazy-evaluation-in-ruby/" rel="nofollow">here</a>.</p>
  
  <p>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.</p>
  
  <p>For example, if I code <code>User.where(some_column: "hello").limit(5)</code>, ActiveRecord will instantiate a query builder, set the conditions about the <code>some_column</code> value and the limited number of results.</p>
  
  <p>But, after executing the <code>.limit(5)</code>, 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?</p>
  
  <p>In the article I've posted above, the author was tricking by calling a final method, <code>each</code> which was executing the request and returning the result.</p>