From 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
Statement
orders = Orders.checks.last_n_days(7)
will result in only one query per database.
How do rails realize this? I am new to Ruby, and I wonder if there is a special construct that allows this to happen.
In order to be able to cling to such methods, the functions generated by named_scope must return themselves or an object, as far as possible. But how does Ruby know that this is the last function call and that he should query the database now?
I ask this because the above statement is actually querying the database, not just returning the SQL statement that results from the chain.
source
share