例如,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
答案 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
的所有记录。