我有几种型号:


用户=普通用户类(不属于任何内容)
挑战=任何形式的竞争(不属于任何事物)
团队=用户列表(属于挑战)
教练=教练的名称和角色,可以在多个团队之间共享,但仅在给定挑战(属于挑战)中存在
TeamCoach =团队和教练之间的关联(属于团队和教练)


我想确保不可能有一个TeamCoach以及一个不属于同一挑战的Team和Coach。

我当前的(有效的)实现如下:

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验证?

谢谢,

最佳答案

您实际上不需要编写自己的验证器类。您可以只使用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

关于ruby-on-rails - 检查两个字段属于同一个对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8799247/

10-12 05:15