首页 > 解决方案 > 跨模型共享属性枚举

问题描述

我正在使用 Enumerize gem,我想创建一个在两个模型之间共享的 Enum。

我的 Enum 模型如下所示:

class StudyTypeEnum < ApplicationRecord

  extends Enumerize
  enumerize :studytype, in: {:full_time, :part_time}

end

然后我只是将它包含在其他模型中

class Course < ApplicationRecord

  include StudyTypeEnum
  ...

我现在不确定如何创建迁移,是否需要在 StudyTypeEnum 和 Course 模型中创建 StudyType 列?

标签: ruby-on-railsrubygems

解决方案


我会担心这种行为。

在文件中:app/models/concerns/enumerable_study.rb

module EnumerableStudy
  extend ActiveSupport::Concern
  extends Enumerize

  included do
    enumerize :studytype, in: {:full_time, :part_time}
  end
end

然后如果您的任何模型需要该字段,只需执行以下操作:

例如在文件中:app/models/course

class Course < ApplicationRecord
  include EnumerableStudy
end

推荐阅读