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
gem Enumerize
使用gem Enumerize实现枚举功能
最新推荐文章于 2024-03-18 09:50:41 发布
这篇博客介绍了如何利用gem Enumerize为ActiveRecord模型添加枚举特性。通过`_define_activerecord_scope_methods!`方法定义了`with_#{name}`和`without_#{name}`两个范围查询方法,用于根据枚举属性进行筛选。此外,还展示了在`good`模型中如何应用enumerize,并定义了`ours_goods`和`card_goods`方法来筛选特定类型的商品。
131

被折叠的 条评论
为什么被折叠?



