如何通过Rails的特殊格式从Postgresql的时间戳类型中选择?

时间:2014-12-25 09:16:38

标签: ruby-on-rails postgresql sqlite

例如,created_at值为2014-12-25 01:02:03,我想从数据库中获取所有与2014-12一样的created_at数据。

如果是SQLite,代码如下:

Model.where("created_at like ?", '2014-12' + "%")
但是当PostgreSQL,怎么办?


加成

从日志中我发现:

HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
Blog Load (1.5ms)  SELECT  "blogs".* FROM "blogs" WHERE (created_at like '2014-12%')  ORDER BY created_at DESC LIMIT 30 OFFSET 0
Completed 500 Internal Server Error in 58ms
ActionView::Template::Error (PG::UndefinedFunction: ERROR:  operator does not exist: timestamp without time zone ~~ unknown

1 个答案:

答案 0 :(得分:1)

在Postgres中获取created_at喜欢2014-12您可以使用Postgres#date_part()的所有数据:

.where("date_part('year', created_at) = ? and date_part('month', created_at) = ?", '2014' , '12')

此查询会返回年created_at等于2014且月份等于12的所有记录。