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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. I also found this question and answer helpful.
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

2 Comments

It wont work because enum is defined in ActiveRecord::Enum. So I get this error : <module:MyEnums>': undefined method enum' for MyEnums:Module (NoMethodError)
enum class macro available only in ActiveRecord.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.