Rails has_many,如何实现嵌套关联?

时间:2017-08-09 06:45:48

标签: ruby-on-rails activerecord associations has-many-through has-many

我正在尝试通过关联实现嵌套的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)

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

如果您正确设置了迁移,则此示例应该有效。