如何在无表Rails 4模型中添加枚举支持



我正在尝试创建一个不受数据库表支持的模型。实质上,模型表示由数据库支持的模型的特定类型的实例。 数据库支持的模型称为计划,非支持的模型称为预留。

计划模型如下所示:

class Schedule < ActiveRecord::Base
  validates :scheduled_date, :presence => true
  ...
  def self.TIME_PERIODS
    @@TIME_PERIODS ||= { time_period_custom: 1, time_period_am: 2, time_period_pm: 3, time_period_all_day: 4 }
  end
  enum time_period: Schedule.TIME_PERIODS
  enum entry_type: { entry_type_reservation: 1, entry_type_blackout: 2 }
  ...
end

预留模型如下所示:

class Reservation
  include ActiveModel::Validations
  include ActiveModel::Conversion
  include ActiveModel::Model
  include ActiveRecord::Enum
  extend ActiveModel::Naming
  attr_reader :id, :entry_type
  attr_accessor: :schedule_date, :time_period
  validates :scheduled_date, :presence => true
  ...
  enum time_period: Schedule.TIME_PERIODS
  ...
end

这将生成运行时错误:NoMethodError:保留:类的未定义方法"枚举"

有没有办法在非从 ActiveRecord 派生的模型中添加对枚举的支持?

你需要

extend,而不是include ActiveRecord::Enum,因为enum是一个类方法。但即便如此,它也不会起作用,因为它依赖于ActiveRecord的其他东西。我无法让枚举在非AR模型中工作。:(

最新更新