2012-12-27 41 views
9

我想動態生成示波器。比方說,我有以下型號:在導軌模型中動態生成示波器

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 

我們可以更換的scope調用的東西基礎上,不斷POSSIBLE_SIZES?我認爲我違反DRY重複他們。

回答

27

你可以做

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

非常整潔,非常感謝! (而且,我知道有關論據的範圍,我認爲這在我的具體情況中更清晰) – spike

2

,你可以做一個循環

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