gpt4 book ai didi

ruby-on-rails - 事件记录查询和 heroku 问题。

转载 作者:行者123 更新时间:2023-11-29 12:34:13 25 4
gpt4 key购买 nike

我只是想运行一个查询来查找数据库中“日期时间”列中的值小于当前 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'

有什么想法吗?

最佳答案

你应该使用 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')

这里有几个教训:

  1. 如果您要部署到 Heroku,您还应该开始在 PostgreSQL 之上进行开发,ActiveRecord 不会让您远离各种数据库之间的所有差异。
  2. 您应该让 ActiveRecord 尽可能地担心类型转换问题,如果您要与日期或时间进行比较,请使用占位符并将某种时间对象交给 AR,让 AR 来解决。
  3. 尽可能使用占位符而不是字符串插值。

关于ruby-on-rails - 事件记录查询和 heroku 问题。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8612938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com