Ruby on Rails Global ActiveRecord::Enum

2020-03-19 04:07发布

问题:

I really like Rails 4 new Enum feature, but I want to use my enum

enum status: [:active, :inactive, :deleted]

in every model. I cannot find any way how to declare for example in config/initializes/enums.rb and include every model

I'm very new in Ruby on Rails and need your help to find solution

回答1:

Use ActiveSupport::Concern this feature created for drying up model codes:

#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



回答2:

I think you could to use a module containing this enum then you can include in each module you want to use:

# 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