ruby on rails named scope implementation
- by Engwan
From the book Agile Web Development With Rails
class Order < ActiveRecord::Base
named_scope :last_n_days, lambda { |days| {:conditions =>
['updated < ?' , days] } }
named_scope :checks, :conditions => {:pay_type => :check}
end
The statement
orders = Orders.checks.last_n_days(7)
will result to only one query to the database.
How does rails implement this? I'm new to Ruby and I'm wondering if there's a special construct that allows this to happen.
To be able to chain methods like that, the functions generated by named_scope must be returning themselves or an object than can be scoped further. But how does Ruby know that it is the last function call and that it should query the database now?
I ask this because the statement above actually queries the database and not just returns an SQL statement that results from chaining.