← Back to Upcase

Creating custom model associations


(Nicolo) #1

In my application a user has a roster of players for specific games in the form of a pick model. I also have game stats for a player for a specific game. I want to create a relationship where a pick has_one game stat for the purpose of using includes to eager load the game_stats for a pick.

Is there a way to create a relationship between tables that share multiple foreign keys from other models?

Here is what I’m going for:

Model Pick
has_one :game_stat
id, game_id, player_id

Model GameStat
id, game_id, player_id, stats


(Qleonetti ) #2

If I understood your question well, I think that what you are looking for are polymorphic associations.

You can have some great examples here :
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

Hopefuly it will be helpful :smiley:


(Nicolo) #3

@qleonetti I’m not seeing how polymorphic associations work in the case. Can you explain how to apply this to my situation?