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

**URL:** <https://www.ruby-forum.com/t/how-to-specify-a-3-way-relation-in-active-record/76021>\
**Category:** Rails\
**Created:** [November 15, 2006, 10:05am UTC](https://www.ruby-forum.com/t/how-to-specify-a-3-way-relation-in-active-record/76021 "2006-11-15T10:05:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jatinder\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/a88e4f/32.png) [@Jatinder\_S](https://www.ruby-forum.com/u/Jatinder_S)\
**Post date:** [November 15, 2006, 10:05am UTC](https://www.ruby-forum.com/t/how-to-specify-a-3-way-relation-in-active-record/76021/1 "2006-11-15T10:05:18Z")

</div>

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)?

Regards,  
Jatinder

---

<div class="post-metadata">

**Author:** ![Jatinder\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/a88e4f/32.png) [@Jatinder\_S](https://www.ruby-forum.com/u/Jatinder_S)\
**Post date:** [November 15, 2006, 11:05am UTC](https://www.ruby-forum.com/t/how-to-specify-a-3-way-relation-in-active-record/76021/2 "2006-11-15T11:05:33Z")

</div>

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  
end  
class Project  
has\_many :project\_memberships  
has\_many :users, :through =\> :project\_memberships  
end  
class ProjectMembership  
belongs\_to :user  
belongs\_to :project  
belongs\_to :role  
end  
class Role  
has\_many :project\_memberships  
end

the table “project\_memberships” should look something like this:  
id #primary key, auto increment  
user\_id  
project\_id  
role\_id  
(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.

> **[BigBold - Informasi Tentang Bisnis dan Marketing](http://www.bigbold.com)**
>
> BigBold ialah situs yang memberikan segala macam Informasi Tentang Bisnis dan Marketing
