【问题标题】:Where date is bigger than in Rails 4 and Postgres日期比 Rails 4 和 Postgres 大的地方
【发布时间】:2015-11-23 23:23:12
【问题描述】:

我正在尝试在我的 rails 4 应用程序中在此模型上触发一个活动记录查询:

Period(id: integer, from: date, to: date, created_at: datetime, updated_at: datetime)

查询应该返回所有尚未结束的期间,因此:to-date 应该大于当前日期:

    Period.where("to >?", Date.today)

And I am getting this error:

  irb(main):011:0> Period.all.where("from > ?", Date.today)
  Period Load (1.0ms)  SELECT "periods".* FROM "periods"  WHERE (from > '2015-11-24')
  Period Load (1.0ms)  SELECT "periods".* FROM "periods"  WHERE (from > '2015-11-24')
PG::SyntaxError: FEHLER:  Syntaxfehler bei "from"
LINE 1: SELECT "periods".* FROM "periods"  WHERE (from > '2015-11-24...
                                                  ^
: SELECT "periods".* FROM "periods"  WHERE (from > '2015-11-24')
PG::SyntaxError: FEHLER:  Syntaxfehler bei "from"
LINE 1: SELECT "periods".* FROM "periods"  WHERE (from > '2015-11-24...
                                                  ^

由于它说语法错误,我假设 postgres 使用的语法与 sql 不同,但我无法在网上找到正确的方法。

在此不胜感激!

【问题讨论】:

    标签: database postgresql ruby-on-rails-4


    【解决方案1】:

    from 是 SQL 保留字,所以会遇到解析错误。

    你需要引用它:

    Period.where('"from" > ?', Date.today)

    在 Postgres 中,双引号 " 是您转义保留字、列名等的方式。

    【讨论】:

    • 谢谢,你拯救了我的夜晚:D
    • 对于大于或等于很简单,只需添加相应的符号>= 而不是> 或者我需要做其他事情吗?
    • 顺便说一句,无需添加all。 Period.where 就足够了。
    猜你喜欢
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多