2014-03-26 54 views
0

我有一個是出口一些列的觀點,一列被稱爲比較日期從數據庫

'created_at' type:"timestamp without timezone" format: "2014-03-20 12:46:36.590253"

在軌我有一個方法,它是從視圖中獲取數據,並試圖篩選數據由一個日期。我試圖將created_at敲入date(),但仍然無法正常工作。 有什麼建議嗎?

return ActiveRecord::Base.connection.select_all(" select * from db_functions where date(created_at) >= #{date_p} AND date(created_at) <= #{date_p}")

PG::UndefinedFunction: ERROR: operator does not exist: date >= integer 
LINE 2: ...select * from db_functions where date(created_at) >= 2014-03... 
                 ^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 

回答

1

第一個明顯的問題是,你的時間沒有加引號。這導致時間被視爲整數。爲了解決這個問題,你可以簡單地包裹date_p用引號或使用ActiveReocrd::ConnectionAdapters#quote爲:

conn = ActiveRecord::Base.connection 
return conn.select_all("select * from db_functions 
         where date(created_at) >= #{conn.quote(date_p)} 
         AND date(created_at) <= #{conn.quote(date_p)}") 

另一種選擇,而不是在where子句中的created_at轉換爲date,你可以修改date_p要開始一天的值,並移除「日期」轉換。此外,不要直接在查詢中使用值,最好使用prepared statements(鏈接文章已有幾年歷史,但通過示例清楚地說明了準備的語句)。

然後還有將日期時間參數修改爲日期開始的任務。鑑於date_p是一個字符串,而不是一個時間,這裏是你可以做的:

date_p = Time.zone.parse("2014-03-20 12:46:36.590253").beginning_of_day.utc 
return ActiveRecord::Base.connection.select_all("select * from db_functions 
               where created_at >= ? 
               AND created_at <= ?", date_p, date_p)