15

我想动态生成范围。假设我有以下模型:

class Product < ActiveRecord::Base
    POSSIBLE_SIZES = [:small, :medium, :large]
    scope :small, where(size: :small) 
    scope :medium, where(size: :medium) 
    scope :large, where(size: :large) 
end

我们可以scope用基于 POSSIBLE_SIZES 常量的东西替换调用吗?我认为我违反 DRY 重复它们。

4

3 回答 3

38

你可以做

class Product < ActiveRecord::Base
  [:small, :medium, :large].each do |s|
    scope s, where(size: s) 
  end
end

但我个人更喜欢:

class Product < ActiveRecord::Base
  scope :sized, lambda{|size| where(size: size)}
end
于 2012-12-27T21:41:34.903 回答
5

你可以做一个循环

class Product < ActiveRecord::Base
    POSSIBLE_SIZES = [:small, :medium, :large]
    POSSIBLE_SIZES.each do |size|
        scope size, where(size: size)
    end
end
于 2012-12-27T21:40:10.480 回答
5

对于 rails 4+,只需更新 @bcd 的答案

class Product < ActiveRecord::Base
  [:small, :medium, :large].each do |s|
    scope s, -> { where(size: s) } 
  end
end

或者

class Product < ActiveRecord::Base
  scope :sized, ->(size) { where(size: size) }
end
于 2018-09-08T00:35:09.993 回答