具有多个外键的Has_many,belongs_to

Wil*_*les 4 ruby-on-rails foreign-keys has-many belongs-to

我正在尝试通过has_many,belongs_to关系将比赛归因于俱乐部。但是,在比赛中,我需要将俱乐部设置为home_team或away_team。为了解决这个问题,我使用了两个foreign_key。

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
Run Code Online (Sandbox Code Playgroud)

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

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

ERROR:  column matches.club_id does not exist
Run Code Online (Sandbox Code Playgroud)

我该如何改变自己的关系,以便做到这一点?

sun*_*oft 5

我对Rails(3.2)中的Associations和(多个)外键的回答:如何在模型中描述它们并编写迁移只适合您!

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

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
Run Code Online (Sandbox Code Playgroud)

有什么问题吗?

  • 哇,这很有效'has_many:messages,-&gt;(u){unscope(where::user_id).where“ from_id =?或to_id =?”,u.id,u.id}`产生`u.messages消息负载( 15.6毫秒)从“消息”中选择“消息”。(from_id = 1或to_id = 1)` (2认同)