henghonglee
henghonglee

Reputation: 1812

3 table join in rails

I am creating a game where users play different game and can choose their roles within each game(like team fortress).

I have created a 2 table join "games_users"

create_table "games_users", :force => true do |t|
    t.integer  "game_id"
    t.integer  "user_id"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

And managed to establish HABTM relationships between the games and users

game.rb

has_and_belongs_to_many :users

user.rb

has_and_belongs_to_many :games

I would like to add now a roles model(or even a roles string) to the system with a 3 table join , how do I do this?

Upvotes: 1

Views: 83

Answers (1)

Mischa
Mischa

Reputation: 43298

You could replace the games_users table with a roles table and have a has_many :through between User and Game, like this:

class User < ActiveRecord::Base
  has_many :roles
  has_many :games, :through => :roles
end

class Role < ActiveRecord::Base
  belongs_to :user
  belongs_to :game
end

class Game < ActiveRecord::Base
  has_many :roles
  has_many :users, :through => :roles
end

Upvotes: 2

Related Questions