【问题标题】:ActiveRecord::StatementInvalid: PGError: ERROR: operator does not exist: timestamp without time zone >= integerActiveRecord::StatementInvalid: PGError: ERROR: operator does not exist: timestamp without time zone >= integer
【发布时间】:2013-12-16 19:55:12
【问题描述】:

我在比较我的 rails 2 项目中的日期时遇到了问题。在我的一个查询中,条件之一是:

: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,但没有帮助。

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord ruby-on-rails-2


    【解决方案1】:

    您的查询肯定与 ActiveRecord 查询语法相去甚远。假设您至少使用 Rails 3 并且 beginningending 是 Time 对象:

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

    或者你也可以使用BETWEEN传递一个Ruby Range

    Bill.where(created_at: beginning..ending)
    

    请避免像刚才那样在查询中插入值。生成的查询不受 SQL 注入保护。

    您可能还想查看 ActiveRecord 文档以了解如何正确使用它。

    对于 Rails

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

    【讨论】:

    • 对不起,我没有提到我正在使用 rails 2。你有 rails 2 的答案吗?
    • 我更新了答案。我希望语法是正确的,Rails 2 离我的日常生活太远了。随意调整代码并...尽快升级 Rails。
    • 谢谢!修复它的关键更改是条件的传递而不是字符串插值。不知道为什么
    猜你喜欢
    • 2023-03-13
    • 2010-10-20
    • 2018-11-10
    • 2015-10-24
    • 1970-01-01
    • 2016-10-25
    • 2022-09-25
    • 1970-01-01
    • 2012-04-04
    相关资源
    最近更新 更多