2017-08-01 83 views
1

我需要对数据库进行查询并按开始日期筛选Event,但列类型为DateTime。 我做模型范围:Rails在'where'查询中将日期时间转换为日期

scope :day, -> (start_date) {where start_date: start_date} 

它工作正常的相同日期时间价值,但我需要一个过滤器,以获得Event只有日期,没有日期时间。

我有PG数据库,并尝试:

scope :day, -> (start_date) {where("start_date:date =?", "#{start_date.to_date}")} 

,但我得到一个错误

+0

威尔这样的事情对你的工作:'这里('DATE(启动)=?',start_date.to_date)'你在Rails 5.1吗? – Deep

回答

4

如果您希望将数据库值转换为一个日期,你必须对不同的数据库服务器做不同的事情像MySQL的下列内容:

scope :day, -> (start_date) {where("DATE(start_date) = ?", start_date)} 

因此可能更明智的您的起始日期参数转换为日期时间:

scope :day, -> (start_date) {where start_date: start_date.to_datetime} 

此外,BigRon posted一个很好的方法来开始和一天的结束,深posted为Rails 5.1的辅助,可以简化这一做法进一步之间的过滤器,但你真的应该考虑你的数据库列是否需要实际日期时间,如果你想单独过滤日期。

+0

谢谢,数据库字段必须有日期时间类型,因为在此字段中我存储开始日期和开始时间 – dendomenko

2

您可以使用范围的一天开始到一天结束:

scope :day, -> (start_date) {where start_date: start_date.beginning_of_day..start_date.end_of_day} 
7

你可以做这样的:

使用SQL日期函数(依赖于数据库,这是为MySQL):

scope :on_day -> (start_date) { where("DATE(start_date) = ?", start_date.to_date) } 

或者使用范围(所以这将检查使用的日期和时间都只是用一天的开始和结束时间和执行BETWEEN q uery):

scope :day, -> (start_date) { where start_date: start_date.beginning_of_day..start_date.end_of_day } 

或者如果的Rails 5.1(这是Rails的5.1引入了新的帮手):

scope :day, -> (start_date) { where start_date: start_date.all_day } 
相关问题