本文介绍了Howto:今天记录的模型范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,如何将 rails 3 中的范围设置为今天的记录?
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, :conditions => { :created_at => Date.today }
end
推荐答案
由于created_at"列包含日期和时间,但您只需要比较日期,您有两种方法(假设您使用 MySQL):
Since "created_at" column contains date and time, but you need compare only date, you have two ways (I assume you use MySQL) :
- 使用BETWEEN:
scope :today, lambda { WHERE("created_at BETWEEN '#{DateTime.now.beginning_of_day}' AND '#{DateTime.now.end_of_day}'") }
- 使用DATE()函数:
scope :today, lambda { WHERE('DATE(created_at) = ?', Date.today)}
此外,您可以将created_on"列添加到仅包含日期的表中.
also, you can add "created_on" column to the table with date only.
更新:
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) }
这篇关于Howto:今天记录的模型范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!