ruby-on-railsrails-activerecordruby-on-rails-4.2

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)

Solution

  • 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