【问题标题】:How to add existing named_scope to anonymous scope?如何将现有的 named_scope 添加到匿名范围?
【发布时间】:2010-09-17 10:29:31
【问题描述】:

我有一个模型:

class Shirt < ActiveRecord::Base
  named_scope :red, :conditions => { :color => 'red' }
  named_scope :blue, :conditions => { :color => 'blue' }
  named_scope :xl,  :conditions => { :size  => 'xl'  }
end

我忘了,如何轻松地将命名范围添加到现有的匿名范围:

scope = Shirt.scoped({})
#and how to add ie. :red to scope?

【问题讨论】:

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


    【解决方案1】:

    Shirt.scoped({}).red?

    【讨论】:

      【解决方案2】:

      这可以通过以下代码实现:

      named_scope :colour, lambda { |colour_id| {:conditions => ["colour_id = ?", colour_id])}}
      

      您可以链接命名范围:

      Shirt.red.xl
      

      【讨论】:

      • 您发布了,如何创建名称范围,但我想知道如何将现有范围添加到匿名范围。
      • 抱歉 - 误解了。你的意思是: Shirt.scoped({}).red.xl
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      相关资源
      最近更新 更多