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