I have the following models
class School
has_many :classrooms
has_many :communications
end
class Classroom
belongs_to :school
end
class Communication
belongs_to :school
end
At the moment I can have a school_id in communication, however due to business logic I realized that I might have to index the communication also with a classroom, making the models to be like this:
class School
has_many :classrooms
has_many :communications
end
class Classroom
belongs_to :school
has_many :communications
end
class Communication
belongs_to :school
belongs_to :classroom, optional: true
end
What I want is that a communication should always belong to a school, but if it belongs to a classroom i want to make sure that the classroom also belongs to the same school
How can I write a validation for this case?
CodePudding user response:
For this case I ended up creating a custom validator:
class ClassroomValidator < ActiveModel::Validator
def validate(record)
if record.classroom.school.id != record.school.id
record.errors.add :classroom, message: "Invalid relation between classroom and school"
end
end
end
class Communication < ApplicationRecord
belongs_to :school
belongs_to :classroom, optional: true
validates_with ClassroomValidator, if: -> { self.classroom != nil }
end
