ruby on rails named scope implementation

Posted by Engwan on Stack Overflow See other posts from Stack Overflow or by Engwan
Published on 2010-04-09T13:14:58Z Indexed on 2010/04/09 19:33 UTC
Read the original article Hit count: 499

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about named-scope