双 belongs_to 并在 rails 上进行验证

double belongs_to with validation on rails

我有以下型号

   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