# Has\_and\_belongs\_to\_many for 3 entities

**URL:** <https://www.ruby-forum.com/t/has-and-belongs-to-many-for-3-entities/161444>\
**Category:** Rails\
**Created:** [February 26, 2009, 2:58pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-for-3-entities/161444 "2009-02-26T14:58:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pesho318i](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ec9cab/32.png) [@pesho318i](https://www.ruby-forum.com/u/pesho318i)\
**Post date:** [February 26, 2009, 2:58pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-for-3-entities/161444/1 "2009-02-26T14:58:34Z")

</div>

Hello,

in my app, I have users, groups, and grouproles.

Each user can be a member of multiple groups. This I have achieved by  
imposing has\_and\_belongs\_to\_many relationship between users and groups  
(i.e. creating another table groups\_users).

However, each user should have a grouprole for each group he/she  
participates in.  
This means that for every user-group pair there should be a grouprole.  
Could you help me out with solving this, I don’t know how to add this  
relationship between users, groups, and gourproles.

thanks 🙂

---

<div class="post-metadata">

**Author:** ![pesho318i](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ec9cab/32.png) [@pesho318i](https://www.ruby-forum.com/u/pesho318i)\
**Post date:** [February 26, 2009, 3:03pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-for-3-entities/161444/2 "2009-02-26T15:03:35Z")

</div>

What you need is a Membership model that associates a user to a group,  
instead of associating them directly using a HABTM association.

The membership would point to the user, group and also contain that  
member role in the group.

- 

Maurício Linhares  
[http://alinhavado.wordpress.com/](http://alinhavado.wordpress.com/) (pt-br) | [http://blog.codevader.com/](http://blog.codevader.com/)  
(en)

On Thu, Feb 26, 2009 at 10:58 AM, Pesho P.

---

<div class="post-metadata">

**Author:** ![pesho318i](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ec9cab/32.png) [@pesho318i](https://www.ruby-forum.com/u/pesho318i)\
**Post date:** [February 26, 2009, 3:27pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-for-3-entities/161444/3 "2009-02-26T15:27:33Z")

</div>

oh cool, that’s much more straightforward!  
Thanks Mauricio!

MaurÃ­cio Linhares wrote:

> What you need is a Membership model that associates a user to a group,  
> instead of associating them directly using a HABTM association.
> 
> The membership would point to the user, group and also contain that  
> member role in the group.
> 
> - 
> 
> Maurï¿½cio Linhares  
> [http://alinhavado.wordpress.com/](http://alinhavado.wordpress.com/) (pt-br) | [http://blog.codevader.com/](http://blog.codevader.com/)  
> (en)
> 
> On Thu, Feb 26, 2009 at 10:58 AM, Pesho P.
