samedi 29 mai 2021

Single Foregn Key references multiple Tables [Rails6]

I have an application with "Categories" "Players" & "Matches".

I want to create a new Table: "Suggestions", with the params: [name: string, description:text, type:integer, element_id:integer]. Users will be able to create "Suggestions" for a Player, Category or a Match. Where the type:integer indicates if it's a "Category Suggestion"-> 1, "Player Suggestion"->2, "Match Suggestion"-> 3. My question is regarding the "element_id" which is meant to be a foreign_key although this foreign key can be from "Category", "Player" or "Match", depending the "type" of the Suggestion. So basically the question is:

How do I reference Multiple tables with only one foreign key. I though about a solution in the models where I just place the foreign key there, but im not sure if this can cause problems in my application. Also I thought about creating 3 tables CategorySuggestions PlayersSuggestions and MatchesSuggestions but that would just be overkill and I wouldn't like that so much.

Aucun commentaire:

Enregistrer un commentaire