Search code examples
ruby-on-railsmigrationmodels

Rails two to many relationship


I have a problem that I solved in a certain way that is not satisfying.

I have a Game model and in a game there are always two teams involved that are part of Team model. I reference to these teams by ids team1_id and team2_id. From my views whenever I want to pull the entire Team record, I have to do a find every time.

I was wondering if there is any way to reference these two teams without going through a many to many relationship or is it the only way? It would be almost a 2-Many relationship, I know that doesn't exist but I would like to know the best way to solve this kind of problems.

Thank you,

This is a snapshot of my migrations:

create_table :games do |t|
  t.datetime "time"
  t.integer "team1_id"
  t.integer "team2_id"


create_table :teams do |t|
  t.references :city
  t.references :user
  t.string "name", :default => "", :null => false  

Solution

  • The way you have it setup is the right way. On the Game model make two team references, team1 and team2

    class Game 
      belongs_to :team1, class_name: 'Team'
      belongs_to :team2, class_name: 'Team'
    end
    

    Then you can just call team1 an team2 on the game instance and it will pull the teams for you.

    game = Game.first
    game.team1
    game.team2
    

    Or you can drop the team1 and team2 id's from the Game model and create a join table with games and teams, an you'd just call "game.teams"