在Rails模型中动态生成范围 [英] Dynamically generate scopes in rails models

查看:66
本文介绍了在Rails模型中动态生成范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我们可以使用基于POSSIBLE_SIZES常量的内容替换scope调用吗?我认为我违反了DRY的规定,重复了他们.

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

推荐答案

您可以做到

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

这篇关于在Rails模型中动态生成范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆