6

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

Irakli Lekishvili
  • 33,492
  • 33
  • 111
  • 169

2 Answers2

21

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

Community
  • 1
  • 1
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • Great answer. I also found [this question and answer](http://stackoverflow.com/questions/14541823/how-to-use-concerns-in-rails-4) helpful. – Rick Smith Sep 08 '15 at 21:32
0

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