0

我有一个正在导出一些列的视图,其中一列称为

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

在 Rails 中,我有一个方法,它从视图中获取数据并尝试按日期过滤数据。我尝试将 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.
4

1 回答 1

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)}")

另一种选择,而不是将每个转换created_atdateinwhere子句,您可以修改date_p为一天的开始值并完全删除“日期”转换。此外,与其直接在查询中使用值,不如使用准备好的语句(链接的文章已有几年的历史,但通过示例清楚地解释了准备好的语句)。

然后还有将日期时间参数修改为一天开始的任务。鉴于这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)
于 2014-03-26T16:03:37.957 回答