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
  • 30,374
  • 32
  • 106
  • 166

2 Answers2

20

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
Зелёный
  • 38,521
  • 9
  • 76
  • 90
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