How to specify a 3-way relation in Active Record?

I have 3 database tables, Users, Projects and Roles.There is a 3-way relation between them which indicates with what role a user is allocated to a specific project.

I have a join table with 3 columns as the foreign key’s to 3 tables mentioned above.

The only solution that comes to my mind is following,

  1. Have a model for the join table having

belongs_to :user,:role,:user

Is there a solution where I can do away with the model for the join table(the way habtm does)?



A user has_many projects, a Project has_many Users, but each role is
associated with 1 user + 1 Project ... i suggest to use has_many
:through and use a join table "project_meberships"

class User
  has_many :project_memberships
  has_many :projects, :through => :project_memberships
class Project
  has_many :project_memberships
  has_many :users, :through => :project_memberships
class ProjectMembership
  belongs_to :user
  belongs_to :project
  belongs_to :role
class Role
  has_many :project_memberships

the table "project_memberships" should look something like this:
id #primary key, auto increment
(additional fields like description)

This assumes you have pre-defined Roles like Admin, Teamleader,
Participant etc. pp. in the roles table.

@user = User.find(1)
role = @user.project_memberships(1).role
project = @user.project_memberships(1).project

You might want to read this about eager loading those associations with
a nested :include in the find command.