Dynamically generate scopes in rails models

若如初见. 提交于 2019-12-20 12:19:40

问题


I'd like to generate scopes dynamically. Let's say I have the following model:

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

Can we replace the scope calls with something based on the POSSIBLE_SIZES constant? I think I'm violating DRY to repeat them.


回答1:


you could do

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

but I personally prefer:

class Product < ActiveRecord::Base
  scope :sized, lambda{|size| where(size: size)}
end



回答2:


you can do a loop

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



回答3:


For rails 4+, just updating @bcd 's answer

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

or

class Product < ActiveRecord::Base
  scope :sized, ->(size) { where(size: size) }
end


来源:https://stackoverflow.com/questions/14061595/dynamically-generate-scopes-in-rails-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!