在Rails模型中动态生成作用域

17

我希望能够动态生成范围。假设我有以下模型:

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

我们能否用基于 POSSIBLE_SIZES 常量的某些内容替换 scope 调用?我认为重复这些调用违反了 DRY 原则。

3个回答

39

你可以做

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

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

5

你可以使用循环

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接