Home > OS >  Single Foregn Key references multiple Tables [Rails6]
Single Foregn Key references multiple Tables [Rails6]

Time:09-17

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. type:integer will indicates what type of suggestion is this

"Category Suggestion" -> 1
"Player Suggestion"   -> 2
"Match Suggestion"    -> 3

My question is, how do I reference multiple tables with only one foreign key(element_id)? This foreign key can be from "Category", "Player" or "Match", depending the "type" of the Suggestion.

I thought about a solution in the models where I just place the foreign key there, but I'm 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.

CodePudding user response:

What you are looking for is Polymorphic Associations. You can add something like,

class Suggestion
  ...
  belongs_to :suggestable, polymorphic: true
  ...
end

In the database, you'll add two columns to the suggestions table.

t.bigint  :suggestable_id
t.string  :suggestable_type

Then you can simply use suggestion.suggestable which will give you the corresponding object of the correct type, without having to manage any of the types or integers yourself.

  • Related