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

标签 ruby-on-rails foreign-keys has-many belongs-to

我试图通过 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/

相关文章:

grails - 将grails hasMany从LinkedHashSet更改为ArrayList

ruby-on-rails - 找不到 Rails 测试表

ruby-on-rails - 用于捕获冒号分隔的键值对的正则表达式,具有多行值

mysql - 如何使用 phpmyadmin 添加删除级联和更新限制?

mysql 外键

c# - SQL错误: Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths. Entity Framework 核心

ruby-on-rails - 强制has_many但只有一个当前关联的 “rails way”是什么?

ruby-on-rails - Mongoid - 保存和 update_attribute 不持久

ruby-on-rails - 错误 : extconf failed, 退出代码 1 [Ruby on Rails]

ruby-on-rails - Ubuntu 11.04 自动测试 + ZenTest + libnotify 不起作用