Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has_many, belongs_to with multiple foreign keys

I'm trying to attribute matches to a club through a has_many, belongs_to relationship. However, in matches, I need to set the club either as a home_team or away_team. To solve this I'm using two foreign_keys.

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

This sets the clubs nicely on the match using home_team_id and away_team_id.

However, I can't access all of a club's matches through Club.matches.

ERROR:  column matches.club_id does not exist

How can I change my relationship so I can do this?

like image 568
Will Viles Avatar asked Feb 14 '23 01:02

Will Viles


1 Answers

My answer to Associations and (multiple) foreign keys in rails (3.2) : how to describe them in the model, and write up migrations is just for you!

As for your code,here are my modifications

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

So any questions?

like image 115
sunsoft Avatar answered Feb 15 '23 14:02

sunsoft