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'。裁判可以作爲第一裁判或第二裁判與比賽相關聯。不確定此修補程序是否有效。 –