检查两个字段是否属于同一对象

时间:2012-01-10 06:08:19

标签: ruby-on-rails ruby-on-rails-3

我有几种型号:

  • User =普通用户类(不属于任何东西)
  • 挑战=任何形式的竞争(不属于任何事情)
  • 团队=用户列表(属于挑战)
  • 教练=教练的名称和角色,可以在多个团队之间共享,但仅适用于特定挑战(属于挑战)
  • TeamCoach =团队与教练之间的关联(属于团队和教练)

我想确保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验证?

谢谢,

1 个答案:

答案 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