Howto: Model scope for todays records

后端 未结 5 1354
后悔当初
后悔当初 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:20

    Since "created_at" column contains date and time, but you need compare only date, you have two ways (I assume you use MySQL) :

    1. use BETWEEN:
      scope :today, lambda { WHERE("created_at BETWEEN '#{DateTime.now.beginning_of_day}' AND '#{DateTime.now.end_of_day}'") }
    2. use DATE() function:
      scope :today, lambda { WHERE('DATE(created_at) = ?', Date.today)}

    also, you can add "created_on" column to the table with date only.

    Updated:

    def self.up
       add_column table_name, :created_on, :date  
       add_column table_name, :updated_on, :date
    end
    

    scope :today, lambda { where(created_on: Date.today) }

提交回复
热议问题