Reputation: 6555
I'm using rails on a legacy database (SQL Server). I'm using the gem composite_primary_keys
also... I'm currently working with two models and the home_games
association works fine, but the home_team
association does not.
class Game < MyDatabaseModel
self.table_name = 'Game'
self.primary_key = 'GameID', 'League'
belongs_to :home_team, class_name: 'Club', foreign_key: 'ClubKey', primary_key: 'Home_Team'
end
class Club < MyDatabaseModel
self.table_name = 'Club'
self.primary_key = 'ClubID', 'Season', 'League'
has_many :home_games, class_name: 'Game', foreign_key: 'Home_Team', primary_key: 'ClubKey'
end
Now when I do myClub.home_games
I get back the expected result of an ActiveRecordRelation of records. However, when I do myGame.home_team
I get a nil object. If I do the following call Club.where(ClubKey: game.Home_Team)
I get the expected result of one record from Club. Are my associations not set up correctly?
Upvotes: 0
Views: 674
Reputation: 3842
Try switching your :foreign_key
and :primary_key
in the belongs_to
call. These should be the same for both the belongs_to
and has_many
calls, since they refer to which foreign key on the "child" table references which primary key on the "parent" table in the relation. In your case:
belongs_to :home_team, class_name: 'Club', foreign_key: 'Home_Team', primary_key: 'ClubKey'
Upvotes: 2