gpt4 book ai didi

ruby-on-rails - Has_many、belongs_to 具有多个外键

转载 作者:行者123 更新时间:2023-12-02 20:33:07 24 4
gpt4 key购买 nike

我试图通过 has_many、belongs_to 关系将比赛归因于俱乐部。然而,在比赛中,我需要将俱乐部设置为 home_team 或away_team。为了解决这个问题,我使用了两个外键。

class Club < ActiveRecord::Base
has_many :matches
end

class Match < ActiveRecord::Base
belongs_to :home_team, class_name: 'Club', foreign_key: 'home_team_id'
belongs_to :away_team, class_name: 'Club', foreign_key: 'away_team_id'
end

使用 home_team_id 和away_team_id 可以很好地设置俱乐部在比赛中的表现。

但是,我无法通过 Club.matches 访问俱乐部的所有比赛。

ERROR:  column matches.club_id does not exist

我如何改变我的关系才能做到这一点?

最佳答案

我对Associations and (multiple) foreign keys in rails (3.2) : how to describe them in the model, and write up migrations的回答只适合你!

至于你的代码,这是我的修改

class Club < ActiveRecord::Base
has_many :matches, ->(club) { unscope(where: :club_id).where("home_team_id = ? OR away_team_id = ?", club.id, club.id) }, class_name: 'Match'
end

class Match < ActiveRecord::Base
belongs_to :home_team, class_name: 'Club', foreign_key: 'home_team_id'
belongs_to :away_team, class_name: 'Club', foreign_key: 'away_team_id'
end

还有什么问题吗?

关于ruby-on-rails - Has_many、belongs_to 具有多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23514293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com