簡體   English   中英

活動記錄查詢和heroku問題。

[英]Issue with active record querying and heroku.

我只是試圖運行查詢以查找數據庫中“ 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'

有任何想法嗎?

您應該使用占位符以獲取正確的格式並確保正確引用該格式:

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. 盡可能使用占位符而不是字符串插值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM