Ruby on Rails Global ActiveRecord :: Enum
我真的很喜欢Rails 4新的Enumfunction,但我想使用我的枚举
enum status: [:active, :inactive, :deleted]
在每个模型中。 我找不到任何方法如何在config/initializes/enums.rb
并包含每个模型
我是Ruby on Rails
新手,需要你的帮助才能找到解决方案
使用ActiveSupport::Concern
为dry
模型代码而创建的此function:
#app/models/concerns/my_enums.rb module MyEnums extend ActiveSupport::Concern included do enum status: [:active, :inactive, :deleted] end end # app/models/my_model.rb class MyModel < ActiveRecord::Base include MyEnums end # app/models/other_model.rb class OtherModel include MyEnums end
Read more
我认为您可以使用包含此枚举的模块,然后您可以包含在要使用的每个模块中:
# app/models/my_enums.rb Module MyEnums enum status: [:active, :inactive, :deleted] end # app/models/my_model.rb class MyModel < ActiveRecord::Base include MyEnums end # app/models/other_model.rb class OtherModel include MyEnums end