我只是试图运行一个查询来查找数据库中所有记录,这些记录的“datetime”列中的值小于当前的unix时间戳。
目前这是我的代码。它在当地运行良好。
t = Time.new.to_i
Event.where("datetime < #{t}")
当我在heroku控制台中测试时,我收到此错误。
>> Event.where("datetime < #{t}")
ActiveRecord::StatementInvalid: PGError: ERROR: operator does not exist: character varying < integer
LINE 1: SELECT "events".* FROM "events" WHERE (datetime < 132462148...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "events".* FROM "events" WHERE (datetime < 1324621488)
/app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1003:in `async_exec'
/app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1003:in `exec_no_cache'
/app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.1.1/lib/active_record/connection_adapters/postgresql_adapter.rb:591:in `block in exec_query'
/app/.bundle/gems/ruby/1.9.1/gems/activerecord-3.1.1/lib/active_record/connection_adapters/abstract_adapter.rb:244:in `block in log'
有什么想法吗?
答案 0 :(得分:5)
您应该使用placeholder来获得正确的格式并确保其被正确引用:
t = Time.new
events = Event.where("datetime < :t", :t => t)
您无法在PostgreSQL中将timestamp
列与整数进行比较,但您可以在SQLite中进行比较。您必须将timestamp
与另一个timestamp
(或date
)或可以解析为timestamp
的字符串进行比较。这个SQL不起作用:
SELECT "events".* FROM "events" WHERE (datetime < 132462148)
但这些会:
SELECT "events".* FROM "events" WHERE (datetime < '2011-12-23 06:52:25.096869')
SELECT "events".* FROM "events" WHERE (datetime < '2011-12-23')
这里有几个教训: