Paulo
Paulo

Reputation: 35

Users and teams - Many to many relationships Ruby

I have a users table and a teams table. Right now users can only have one team, there's a column in users.team_id. But now I want to make it possible for users to have multiple teams. So I already created a user_teams table with user_id and team_id.

I ran migrations like so:

migrations/create_users_teams

class CreateUsersTeams < ActiveRecord::Migration[5.0]
  def change
    create_table :user_teams do |t|
      t.belongs_to :user, foreign_key: true, null: false
      t.references :team, foreign_key: true, null: false

      t.timestamps null: false
    end
  end
end

And my code is as follows:

models/user.rb

    class User < ApplicationRecord

    #belongs_to :team

    # should now have multiple teams
    has_many :user_teams
    has_many :teams, through: :user_teams

models/team.rb

class Team < ApplicationRecord

has_many :user_teams
has_many :users, through: :user_teams

models/user_teams.rb (new file)

class UserTeam < ApplicationRecord
  belongs_to :user
  belongs_to :team
end

From the tutorials I watched that was all I needed to do, but I'm not populating the table. What am I missing here?

Upvotes: 0

Views: 137

Answers (2)

DevPro
DevPro

Reputation: 511

Make sure your User_Teams table should have user_id and team_id columns.

if you have @user object with you, then

@user.teams << Team.find(some_team_id)

This piece of code will automatically create a new row in the User_Teams table with the right team_id and user_id.

Upvotes: 1

Tom
Tom

Reputation: 1320

User.in_batches.each_record { |user| UserTeam.create(user: user, team_id: user.team_id) }

You are going to need to populate the new UserTeam table after the migration is completed. You can either do this in the migration itself or via console or a rake task.

After you have populated the UserTeam table you will want to drop the users.team_id column.

I would also add index: true to both id columns of UserTeam.

Upvotes: 0

Related Questions