gem Enumerize

这篇博客介绍了如何利用gem Enumerize为ActiveRecord模型添加枚举特性。通过`_define_activerecord_scope_methods!`方法定义了`with_#{name}`和`without_#{name}`两个范围查询方法,用于根据枚举属性进行筛选。此外,还展示了在`good`模型中如何应用enumerize,并定义了`ours_goods`和`card_goods`方法来筛选特定类型的商品。
Gem Enumerize:枚举

  # without_#{name}with_#{name}俩个方法不是rais自带的是gem  enumerize提供的
  # 具体源码位置:lib/enumeriza/scope/active_record.rb
  # 具体实现方法使用define_singleton_method 定义单例方法
  #
  # def _define_activerecord_scope_methods!(name, options)
  #  scope_name = options[:scope] == true ? "with_#{name}" : options[:scope]

  #  define_singleton_method scope_name do |*values|
  #    values = enumerized_attributes[name].find_values(*values).map(&:value)
  #    values = values.first if values.size == 1

  #    where(name => values)
  #  end

  #  if options[:scope] == true
  #    define_singleton_method "without_#{name}" do |*values|
  #      values = enumerized_attributes[name].find_values(*values).map(&:value)
  #      where(arel_table[name].not_in(values))
  #    end
  #  end
  # end

  # autoload 子类礼品
  # in: self.descendants 详情查看 https://github.com/rails/rails/issues/8699
  Dir["#{Rails.root}/app/models/good/*.rb"].each do |file|
    require_dependency file
  end

  enumerize :type, in: self.descendants,
    scope:true,
    i18n_scope: "activerecord.attributes.good/type"

  def self.ours_goods
    without_type(Good::CardGood)
  end

  def self.card_goods
    with_type(Good::CardGood)
  end
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值