在rails模型中动态生成范围

spi*_*ike 12 ruby metaprogramming ruby-on-rails ruby-on-rails-3 rails-activerecord

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

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
Run Code Online (Sandbox Code Playgroud)

我们可以scope用基于POSSIBLE_SIZES常量的东西替换调用吗?我想我是在违反DRY来重复它们.

bcd*_*bcd 31

你能做到的

class Product < ActiveRecord::Base
  [:small, :medium, :large].each do |s|
    scope s, where(size: s) 
  end
end
Run Code Online (Sandbox Code Playgroud)

但我个人更喜欢:

class Product < ActiveRecord::Base
  scope :sized, lambda{|size| where(size: size)}
end
Run Code Online (Sandbox Code Playgroud)


Llu*_*uís 5

你可以做一个循环

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


use*_*149 5

对于 Rails 4+,只需更新 @bcd 的答案

class Product < ActiveRecord::Base
  [:small, :medium, :large].each do |s|
    scope s, -> { where(size: s) } 
  end
end
Run Code Online (Sandbox Code Playgroud)

或者

class Product < ActiveRecord::Base
  scope :sized, ->(size) { where(size: size) }
end
Run Code Online (Sandbox Code Playgroud)