【发布时间】:2017-08-09 06:45:47
【问题描述】:
我正在尝试通过关联来实现嵌套的 has_many。我需要通过 Umpire 在 Team 和 Match 之间建立关联。我没有通过关联使用 rails 5 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)
【问题讨论】:
标签: ruby-on-rails activerecord associations has-many-through has-many