我试图通过关联实现嵌套has_many。我需要通过裁判建立团队和比赛之间的联系。我无法通过关联使用rails 5 has_many来完成它。Rails has_many,如何实现嵌套关联?
这里是我的模型:
class Team < ApplicationRecord
has_many :umpires
has_many :matches, through: :umpires
end
class Umpire < ApplicationRecord
belongs_to :team
has_many :matches, -> (umpire){ unscope(where: :umpire_id).where('matches.first_umpire_id = :umpire_id OR matches.second_umpire_id = :umpire_id', umpire_id: umpire.id,)}
end
class Match < ApplicationRecord
# first_umpire_id (integer)
# second_umpire_id (integer)
end
对我来说Umpire.first.matches
作品,但是当我尝试Team.first.matches
我收到以下错误:
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'matches.umpire_id' in 'on clause': SELECT `matches`.* FROM `matches` INNER JOIN `umpires` ON `matches`.`umpire_id` = `umpires`.`id` WHERE `umpires`.`team_id` = 1 AND (matches.first_umpire_id = 1 OR matches.second_umpire_id = 1)
一场比赛有两个裁判,'first_umpire_id','second_umpire_id'。裁判可以作为第一裁判或第二裁判与比赛相关联。不确定此修补程序是否有效。 –