2013-07-19 19 views
0

我需要使用默認created_at Rails字段獲取僅包含在時間範圍內的記錄。這一天無論如何都沒有創造。如何比較在rails上使用created_at字段的時間範圍

我有這樣的:

@start_time = test.start_time.strftime("%I:%M%p") 
@end_time test.end_time.strftime("%I:%M%p") 
@websites = device.websites.where(:created_at => @[email protected]_time) 

我正在尋找這樣的事情:

@websites = device.websites.where(:created_at::time => @[email protected]_time) 

這不產生這種結果的SQL語句。

SELECT DISTINCT `websites`.* FROM `websites` WHERE `websites`.`device_id` = 2 AND (`websites`.`created_at` BETWEEN '16:10:00' AND '21:10:00') 

但是,如果我將時間函數添加到created_at字段,工作正常。

SELECT DISTINCT `websites`.* FROM `websites` WHERE `websites`.`device_id` = 2 AND (time(`websites`.`created_at`) BETWEEN '16:10:00' AND '21:10:00') 

Rails最好的方式是做什麼的?

+0

可能重複[我如何搜索日期範圍內具有可變日期的Rails(http://stackoverflow.com/questions/5284696/how-can-i搜索日期範圍在鋼軌與可變日期) – Benj

回答

1

Rails會自動將時間對象轉換爲數據庫所需的格式,因此不需要strftime。你應該能夠做到這一點是這樣的:

@websites = device.websites.where(:created_at => test.start_time..test.end_time) 
+0

感謝您的回答! – jgiunta

+0

我嘗試它但不工作,如果我使用mysql時間函數來轉換created_at字段工作正常。 – jgiunta