在rails上进行双重belong_to验证



我有以下型号的

class School
has_many :classrooms
has_many :communications
end
class Classroom
belongs_to :school
end
class Communication
belongs_to :school
end

目前,我可以在通信中使用school_id,但由于业务逻辑的原因,我意识到我可能还必须对教室的通信进行索引,使模型如下所示:

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

我想要的是,沟通应该始终属于一所学校,但如果它属于一个教室,我想确保这个教室也属于同一所学校

我如何为这个案例编写验证?

对于这个案例,我最终创建了一个自定义验证器:

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

相关内容

最新更新