I have several models:
- User = an ordinary user class (does not belong to anything)
- Challenge = any sort of competition (does not belong to anything)
- Team = a list of users (belongs to Challenge)
- Coach = name and role of a coach, which can be shared between several teams, but exists only for a given Challenge (belongs to Challenge)
- TeamCoach = an association between Team and Coach (belongs to Team and Coach)
I want to make sure that it is impossible to have a TeamCoach with a Team and a Coach that do not belong to the same Challenge.
My current (working) implementation is the following:
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
Is there a shorter, more elegant way to do the SameChallengeValidator validation?
Thanks,
You don’t really need to write your own validator class. You can just use the validate method instead: