【问题标题】:Rails has_many, how to achieve nested association?Rails has_many,如何实现嵌套关联?
【发布时间】: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


    【解决方案1】:

    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
    

    如果您正确设置了迁移,则此示例应该可以工作。

    【讨论】:

    • 一场比赛有两个裁判,first_umpire_idsecond_umpire_id。裁判可以作为第一裁判或第二裁判与比赛相关联。不确定此修复是否有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多