我正在尝试通过关联实现嵌套的has_many。我需要通过裁判建立团队和比赛之间的关联。我没有通过关联使用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)
答案 0 :(得分: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
如果您正确设置了迁移,则此示例应该有效。