我想动态生成作用域。假设我有以下模型:
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
关于ruby-on-rails - 在 Rails 模型中动态生成范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14061595/