2014-03-26 58 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)