2013-12-16 45 views
0

我在我的rails 2項目中比較日期時遇到問題。在我的查詢之一,條件之一是這樣的:ActiveRecord :: StatementInvalid:PGError:錯誤:運算符不存在:timestamp without time zone> =整數

:conditions => ["bills.created_at >= #{beginning.to_s.delete("-")} AND bills.created_at <= #{ending.to_s.delete("-")}"] 

我分別將它傳遞"2013-10-16""2013-12-15"beginningending。這工作在我的舞臺環境,但在我的生產環境中被破壞:

ActiveRecord::StatementInvalid: PGError: ERROR: operator does not exist: timestamp without time zone >= integer 
    LINE 1: SELECT * FROM "bills" WHERE (created_at >= 20131016) 

我該如何解決這個問題?我看到這個heroku Postgres error - operator does not exist timestamp without timezone = integer但它沒有幫助。

回答

1

您的查詢與ActiveRecord查詢語法絕對相差甚遠。假設你正在使用至少Rails 3的和beginningending有時間對象:

Bill.where("created_at >= ? AND created_at <= ?", beginning, ending) 

,或者您也可以使用BETWEEN傳遞一個Ruby Range

Bill.where(created_at: beginning..ending) 

請避免在喜歡你的查詢插入值剛剛做到了。所得到的查詢不受SQL注入保護。

您可能還想查看ActiveRecord文檔以瞭解一點如何正確使用它。

For Rails < 3您應該將條件傳遞給find方法。

Bill.find(:all, :conditions => "created_at >= ? AND created_at <= ?", beginning, ending) 
+0

對不起,我沒有提到我使用導軌2.你有一個導軌2的答案? – Edmund

+0

我更新了答案。我希望語法是正確的,Rails 2離我的日常工作太遠了。隨意修改相應的代碼,並儘快升級Rails。 –

+0

謝謝!固定它的關鍵變化是通過條件而不是字符串插值。不知道爲什麼 – Edmund

相關問題