我有以下型號
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
我想要的是通信應該始終屬于一所學校,但如果它屬于一個教室,我想確保該教室也屬于同一所學校
我該如何為這種情況撰寫驗證?
uj5u.com熱心網友回復:
對于這種情況,我最終創建了一個自定義驗證器:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/419430.html
標籤:
