when you have matching associations, the foreign_key
and primary_key
for those associations are the same. so just swap the foreign_key
and primary_key
in the belongs_to
association.
Belongs_to association with primary key and foreign key
-
25-06-2023 - |
Question
So I am doing a application where I have a "Game" Model that has 4 attributes from from 4 different users. One of those attributes is the player_id, and the other 3 are users uid (String id given by facebook).
Both models go like this:
class Game < ActiveRecord::Base
belongs_to :player, class_name: "User"
belongs_to :gamer_one, class_name: "User", primary_key: "gamer_one", foreign_key: "uid"
belongs_to :gamer_two, class_name: "User", primary_key: "gamer_one", foreign_key: "uid"
belongs_to :gamer_three, class_name: "User", primary_key: "gamer_one", foreign_key: "uid"
end
class User < ActiveRecord::Base
has_many :games, foreign_key: 'player_id'
has_many :game_ones, class_name: 'Game', foreign_key: 'gamer_one', primary_key: 'uid'
has_many :game_twos, class_name: 'Game', foreign_key: 'gamer_two', primary_key: 'uid'
has_many :game_threes, class_name: 'Game', foreign_key: 'gamer_three', primary_key: 'uid'
end
When I go to the console and check for User.game_ones, User.game_twos, or User.game.threes, I get the exact relation I want, but if I make it backwards (Game.gamer_one, Game.gamer_two, Game.gamer_three) I just get null, and the query is doing is wrong.
Any idea if the belongs_to relation I'm doing is wrong in some point?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow