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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With