Rails: Share enum declaration values between models
Asked Answered
S

2

22

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)
Shelter answered 4/4, 2015 at 20:38 Comment(0)
A
34

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
Affettuoso answered 4/4, 2015 at 20:48 Comment(2)
Almost correct, with a small mistake! Your example will return an array of strings, not array of symbols. %w must be changed to %i.Akerley
This solution requires both enums to be attached to fields of the same name.Lapful
M
15

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
Milreis answered 27/6, 2017 at 19:1 Comment(3)
You should use the plural form of the field name in SomeOtherClassLapful
This seems like the way to go if you need the fields to have different names.Oldfangled
My enum is called kind, and SomeOtherClass.kinds worked perfectly.Leverhulme

© 2022 - 2024 — McMap. All rights reserved.