Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Share enum declaration values between models

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)
like image 557
Fellow Stranger Avatar asked Apr 04 '15 20:04

Fellow Stranger


2 Answers

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
like image 53
lunr Avatar answered Nov 18 '22 09:11

lunr


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
like image 13
MegaTux Avatar answered Nov 18 '22 09:11

MegaTux