Rails:在模型之间共享枚举声明值

问题描述 投票:16回答:2

我将enum应用于以下属性:transparency

在两个不同的模型中使用相同的属性(带有枚举):CategoryPost

是否有可能在模型之间共享枚举值,以避免代码重复:

enum transparency: %w(anonymous private public)
ruby-on-rails rails-activerecord ruby-on-rails-4.2
2个回答
22
投票

您可以使用concern

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

然后将其包含在模型中:

class Category < ActiveRecord::Base
  include HasTransparency

  ....
end

7
投票

使用关注点或模块的“正确方法”的替代方法,您可以仅引用另一个类的枚举。它对我来说非常有效:

enum same_values_than_other: SomeOtherClass.my_awesome_enum
© www.soinside.com 2019 - 2024. All rights reserved.