ruby on rails named scope implementation

后端 未结 3 1678
小鲜肉
小鲜肉 2021-02-06 18:34

From the book Agile Web Development With Rails

class Order < ActiveRecord::Base
   named_scope :last_n_days, lambda { |days| {:conditions =>
      [\'updat         


        
3条回答
  •  無奈伤痛
    2021-02-06 18:52

    You might want to try this

    class Order < ActiveRecord::Base
    
      class << self
        def last_n_days(n)
          scoped(:conditions => ['updated < ?', days])
        end
        def checks
          scoped(:conditions => {:pay_type => :check})
        end
      end
    
    end
    

    usage is the same

    @orders = Order.last_n_days(5)
    @orders = Order.checks
    @orders = Order.checks.last_n_days(5)
    

    This still does all the lazy loading you love. That is, it won't make a query until you attempt to access the records. Bonus: Rails 3 compatible!

    Named Scopes Are Dead

提交回复
热议问题