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

Mik*_*ike 5 ruby-on-rails ruby-on-rails-4

我正在尝试创建一个不受数据库表支持的模型。本质上,模型表示由数据库支持的模型的特定类型的实例。由 db 支持的模型称为 Schedule,无支持的模型称为 Reservation。

Schedule 模型看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

Reservation 模型看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

这会产生一个运行时错误:NoMethodError: undefined method `enum' for Reservation:Class

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

Mla*_*vić 3

您需要extend,而不是include ActiveRecord::Enumenum类方法那样。但即便如此,它也无法工作,因为它依赖于ActiveRecord. 我无法使枚举在非 AR 模型中工作。:(