Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add enum support in a tableless Rails 4 model

I am trying to create a model that is not backed by a database table. Essentially, the model represents a specific type of instance of a model that is backed by the database. The db-backed model is called Schedule, the non-backed model is called Reservation.

The Schedule model looks something like this:

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

The Reservation model looks something like this:

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

This generates a run-time error: NoMethodError: undefined method `enum' for Reservation:Class

Is there a way to add support for enums in a model not derived from ActiveRecord?

like image 251
Mike Avatar asked Oct 31 '22 08:10

Mike


1 Answers

You need to extend, not include ActiveRecord::Enum, as enum is a class method. But even then, it won't work as it relies on other stuff from ActiveRecord. I wasn't able to make enums work in non-AR model. :(

like image 147
Mladen Jablanović Avatar answered Nov 15 '22 12:11

Mladen Jablanović