0

我试图通过关联实现嵌套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)

回答

0

Umpire模型应该有两个belongs_to的关系,一个是Team型号和Match型号。另外,如果您想在两个方向上均可访问,则Match模型也应该具有has_many through关联。

的代码应该是这样的:如果你有你的迁移设置正确

class Team < ApplicationRecord 
    has_many :umpires 
    has_many :matches, through: :umpires 
end 

class Umpire < ApplicationRecord 
    belongs_to :team 
    belongs_to :match 
end 

class Match < ApplicationRecord 
    has_many :umpires 
    has_many :teams, through: :umpires 
end 

这个例子应该工作。

+0

一场比赛有两个裁判,'first_umpire_id','second_umpire_id'。裁判可以作为第一裁判或第二裁判与比赛相关联。不确定此修补程序是否有效。 –