在rails模型中动态生成范围

时间:2012-12-27 21:33:56

标签: ruby-on-rails ruby ruby-on-rails-3 rails-activerecord metaprogramming

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

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 个答案:

答案 0 :(得分:31)

你可以做到

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

答案 1 :(得分:4)

你可以做一个循环

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

答案 2 :(得分:3)

对于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