我想动态生成范围。假设我有以下模型:
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来重复它们。
答案 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