Share enum declaration values between models

こ雲淡風輕ζ 提交于 2019-12-20 17:59:31

问题


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)

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/29451169/share-enum-declaration-values-between-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!