【问题标题】:2 belongs_to, 1 has_many : Team/Game relationship [duplicate]2belongs_to,1has_many:团队/游戏关系[重复]
【发布时间】:2016-03-27 21:28:38
【问题描述】:

我有两个模型游戏和团队:

    class Game < ActiveRecord::Base
      belongs_to :home_team, class_name: 'Team', required: true
      belongs_to :visitor_team, class_name: 'Team', required: true
    end

    class Team < ActiveRecord::Base
      has_many :games
    end

关系 has_many :games 不起作用(我必须指定 class_name 但在这种情况下我有两个类名)。我必须区分家和访客。

关于如何设计这个的任何想法?

谢谢

【问题讨论】:

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


    【解决方案1】:

    has_many 将查找与您正在使用的类同名的外键。

    在这种情况下,Rails 将假定关联的 Game 类中有一个 team_id,链接回团队。情况并非如此,因此您需要更加明确。

    在这种情况下,您也没有从游戏返回到团队的单一链接。 Game 和 Team 之间有两个不同的链接,因此您需要将这两个链接都表示为关联:

    class Team < ActiveRecord::Base
      has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
      has_many :visitor_games, class_name: 'Game', foreign_key: :visitor_team_id
    end
    

    如果您想获取给定球队的所有比赛,无论是主场比赛还是客场比赛,您都可以定义一个方法:

    class Team < ActiveRecord::Base
      has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
      has_many :visitor_games, class_name: 'Game', foreign_key: :visitor_team_id
    
      def games
        Game.where('home_team_id = ? or visitor_team_id = ?', id, id)
      end
    end
    

    【讨论】:

    • 谢谢! :) 这正是我目前所拥有的,但我希望用漂亮的 has_many 替换我的“游戏”方法。
    【解决方案2】:

    您必须指定foreign_key,假设您在games 表中有home_team_idvisitor_team_id 列:

    has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
    has_many :visitor_games, class_name: 'Game', foreign_key: :visitor_team_id
    

    【讨论】:

    • 这是错误的。与belongs_to的声明无关。
    • 您好,感谢您的回复。然而,foreign_key 在这里并没有改变任何东西。我仍然收到“SQLException:没有这样的列:games.team_id”。我认为问题可能出在 has_many 的声明中,但我不知道缺少什么。
    • 对不起,复制错误的行进行编辑...我已经更新了我的答案。
    猜你喜欢
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多