我有几种型号:
我想确保TeamCoach的团队和教练不属于同一个挑战赛。
我目前的(工作)实施如下:
class TeamCoach < ActiveRecord::Base
attr_readonly :coach_id, :team_id
belongs_to :coach
belongs_to :team
validates :coach_id, :presence => true,
:uniqueness => { :scope => :team_id }
class SameChallengeValidator < ActiveModel::Validator
def validate(team_coach)
if team_coach.team.challenge_id != team_coach.coach.challenge_id
team_coach.errors[:base] << "The team and coach do not belong to the same challenge."
end
end
end
validates_with SameChallengeValidator
end
是否有更简洁,更优雅的方式进行SameChallengeValidator验证?
谢谢,
答案 0 :(得分:3)
你真的不需要编写自己的验证器类。您只需使用validate方法:
class TeamCoach < ActiveRecord::Base
attr_readonly :coach_id, :team_id
belongs_to :coach
belongs_to :team
validates :coach_id, :presence => true,
:uniqueness => { :scope => :team_id }
validate :team_and_coach_belong_to_same_challenge
private
def team_and_coach_belong_to_same_challenge
errors.add(:base, "The team and coach do not belong to the same challenge.") if self.team.challenge_id != self.coach.challenge_id
end
end