Home > Mobile >  Ruby - migration reference represented in model
Ruby - migration reference represented in model

Time:11-18

Ok, so what I have is:

Two entities: games and apps. They have a relation from apps to games:

  • On the migration it is as follows: add_reference :apps, :games, type: :uuid, foreign_key: true
  • On app model it is like this: belongs_to :game
  • On game model it is like this: has_many :apps

Right now that allows me to have an app and assign it a game (in the DB it shows a new column as game_id on app table).

What I want to do now is add a column with another game called requested_game.

To do that I added the following migration: add_reference :apps, :requested_game, type: :uuid, foreign_key: { to_table: :games }, but now I do not know how to show that relation in the models.

Any ideas? Do I have to create a requested_game model and reference it to the game model? I'm kinda lost right now...

CodePudding user response:

I think this Stackoverflow Answer about multiple foreign keys placed on a single table might get you what you need.

To extrapolate a bit, it sounds like you might ultimately want instances of your App model to have multiple methods attached to it? For example:

new_app = App.first
new_app.game
=> old_game
new_app.requested_game
=> newly_requested_game

If that's what you want then, as explained in the link above, you'll want the apps table to have two foreign keys on it, both pointing to the games table. Naturally, you'll have to give the table columns and corresponding belongs_to methods in the game table the proper options to know which is which.

I don't think you'll need to create a RequestedGame model unless you want to create instances of that model with its own methods and whatnot. So if you wanted to run something like requested_game.app, that model might come in handy.

  • Related