【问题标题】:Rails Scope Not Working When Regular where() Query Does当常规 where() 查询执行时,Rails 范围不起作用
【发布时间】:2012-03-21 18:22:54
【问题描述】:

我正在尝试在我的 Products 类中构建一个相对简单的命名范围。奇怪的是,如果我直接发出查询(例如Product.where()),我会得到我期望的结果。但是,如果将此查询更改为 scope 声明,则结果集为 nil

为什么我的查询在直接调用时可以工作,但在将其放入作用域时却什么也没产生?这是实际的代码:

scope :is_queued, where("status = 2 OR (status = 0 AND status_expires > ?)", DateTime.now )# <-- returns nil
Product.where("status = 2 OR (status = 0 AND status_expires > ?)", DateTime.now) # <-- returns 1+ results (as expected)

谢谢!

汤姆

【问题讨论】:

    标签: sql ruby-on-rails activerecord scopes


    【解决方案1】:

    使用scope 定义的范围会在定义scope 时评估一次 - 因此DateTime.now 指的是您的应用实例首次启动的时间。

    试试:

    scope :is_queued, lambda { where("status = 2 OR (status = 0 AND status_expires > ?)", DateTime.now) }
    

    【讨论】:

    • 原来是这个的组合,加上一个被遗忘的空 is_queued 类方法挂在文件的更深处。哎呀! :-) 谢谢。
    猜你喜欢
    • 2017-08-03
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多