Howto: Model scope for todays records

后端 未结 5 1350
后悔当初
后悔当初 2021-02-08 05:03

Hey, how do I set a scope in rails 3 to todays records?

This doent work, yet. I get no data.

class MyModel < ActiveRecord::Base
    scope :today, :con         


        
5条回答
  •  伪装坚强ぢ
    2021-02-08 05:41

    I think you can define a general scope like this:

    class MyModel < ActiveRecord::Base
      scope :created_on, lambda {|date| {:conditions => ['created_at >= ? AND created_at <= ?', date.beginning_of_day, date.end_of_day]}}
    
      def self.today
        self.created_on(Date.today)
      end
    end
    

    So you can use

    >> MyModel.today #-> records created today
    >> MyModel.created_on(Date.today - 1.week) #-> records created a week ago
    

提交回复
热议问题