Francois Wouts
Francois Wouts

Reputation: 3962

Check that two fields belong to the same object

I have several models:

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,

Upvotes: 3

Views: 273

Answers (1)

iwasrobbed
iwasrobbed

Reputation: 46703

You don't really need to write your own validator class. You can just use the validate method instead:

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

Upvotes: 3

Related Questions