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?
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. :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With