I have a few enums in my project that will be reused across multiple models, and a few of which will have their own internal logic, and so I've implemented them as value objects (as described here @ section 5) but I can't seem to get ActiveRecord validations to work with them. The simplest example is the Person
model with a Gender
value object.
Migration:
# db/migrate/###_create_people.rb
class CreatePeople < ActiveRecord::Migration[5.2]
def change
create_table :people do |t|
t.string :name
t.integer :age
t.integer :gender
end
end
end
Model:
# app/models/person.rb
class Person < ApplicationRecord
validates :gender, presence: true
enum gender: Enums::Gender::GENDERS
def gender
@gender ||= Enums::Gender.new(read_attribute(:gender))
end
end
Value Object:
# app/models/enums/gender.rb
module Enums
class Gender
GENDERS = %w(female male other).freeze
def initialize(gender)
@gender = gender
end
def eql?(other)
to_s.eql?(other.to_s)
end
def to_s
@gender.to_s
end
end
end
The only problem is that despite the model being set to validate the presence of the gender attribute, it allows a Person
to be saved with a gender
of nil
. I'm not sure why that is, so I'm not sure where to start trying to fix the problem.