在rails模型中动态生成范围

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

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来重复它们。

你能做到的

 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 

你可以做一个循环

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

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