简体   繁体   中英

Validate delegated method in Rails

I have the following three models:

class Team < ActiveRecord::Model
  has_many :teams_players
  has_many :players, :through => :teams_players
end

class TeamsPlayer < ActiveRecord::Model
  belongs_to :team
  belongs_to :player

  delegate :position, :to => :player
end

class Player < ActiveRecord::Model
  has_many :teams_players
  has_many :teams, :through => :teams_players

  # the database attribute 'position' exists on Player
end

A team can have multiple players, and a player can belong to multiple teams. However, a team can only have one player with position 'kicker'.

How can I create this unique validation?

I tried adding a validation on TeamsPlayer like this:

validates :position, :uniqueness => { :scope => {:team_id} }

But during the validation, rails runs a query checking the type column on the TeamsPlayer database table. Instead, I want it to recognize that it's a delegated method and check for it on the Player database table instead.

这不是对Player的验证,而是对Team自定义验证

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM