21

I'm applying enum on the following attribute: transparency

The same attribute (with enum) is used in two different models: Category and Post

Is it possible to share the enum values between models, to avoid code duplication:

enum transparency: %w(anonymous private public)
Promise Preston
  • 8,732
  • 5
  • 43
  • 70
Fellow Stranger
  • 25,431
  • 22
  • 134
  • 188

2 Answers2

26

You can use a concern.

module HasTransparency
  extend ActiveSupport::Concern
  included do
    enum transparency: %w(anonymous private public)
  end
end

Then include it in your models:

class Category < ActiveRecord::Base
  include HasTransparency

  ....
end
lunr
  • 4,901
  • 4
  • 28
  • 46
12

An alternative to "the right way" of using a concern or module, you can just make reference to another class enum. It worked perfectly for me:

enum same_values_than_other: SomeOtherClass.my_awesome_enum
MegaTux
  • 1,402
  • 23
  • 24