【问题标题】:Is it possible to invert a named scope in Rails3?是否可以在 Rails3 中反转命名范围?
【发布时间】:2012-03-05 22:22:53
【问题描述】:

在我的 Rails3 模型中,我有这两个命名范围:

scope :within_limit,     where("wait_days_preliminary <= ? ", ::WAIT_TIME_LIMIT.to_i )
scope :above_limit,      where("wait_days_preliminary > ? ",  ::WAIT_TIME_LIMIT.to_i )

基于它们的相似性,我很自然地通过反转第一个来定义第二个。

如何在 Rails 中做到这一点?

【问题讨论】:

    标签: ruby-on-rails-3 named-scope


    【解决方案1】:

    Arel 有一个您可以使用的 not 方法:

    condition = arel_table[:wait_days_preliminary].lteq(::WAIT_TIME_LIMIT.to_i)
    scope :within_limit, where(condition)     # => "wait_days_preliminary <= x"
    scope :above_limit,  where(condition.not) # => "NOT(wait_days_preliminary <= x)"
    

    【讨论】:

    • 聪明!虽然你的回答表明我不能定义第一个,然后只是“不是”第一个范围,像这样:scope :above_limit, within_limit.not
    【解决方案2】:

    我相信这可以工作

    scope :with_limit, lambda{ |sign| where("wait_days_preliminary #{sign} ? ", ::WAIT_TIME_LIMIT.to_i ) }
    
    MyModel.with_limit(">")
    MyModel.with_limit("<")
    MyModel.with_limit(">=")
    MyModel.with_limit("<=")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多