# Double belongs to in AR?

**URL:** <https://www.ruby-forum.com/t/double-belongs-to-in-ar/121517>\
**Category:** Rails\
**Created:** [November 28, 2007, 4:46pm UTC](https://www.ruby-forum.com/t/double-belongs-to-in-ar/121517 "2007-11-28T16:46:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kyle\_s](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f6c823/32.png) [@kyle\_s](https://www.ruby-forum.com/u/kyle_s)\
**Post date:** [November 28, 2007, 4:46pm UTC](https://www.ruby-forum.com/t/double-belongs-to-in-ar/121517/1 "2007-11-28T16:46:23Z")

</div>

Can you do a double belongs to in ActiveRecord? I wanted a column  
made up of user ids matched with group ids (since I can’t think of a  
better way with my current knowledge of AR).

Something like the following:

class User\<ActiveRecord::Base  
has\_many user\_groups  
end

class Group\<ActiveRecord::Base  
end

class UserGroup\<ActiveRecord::Base  
belongs\_to :user  
belongs\_to :group  
end

#how would you make that work?

Thanks,  
Kyle

---

<div class="post-metadata">

**Author:** ![kyle\_s](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f6c823/32.png) [@kyle\_s](https://www.ruby-forum.com/u/kyle_s)\
**Post date:** [November 28, 2007, 4:55pm UTC](https://www.ruby-forum.com/t/double-belongs-to-in-ar/121517/2 "2007-11-28T16:55:15Z")

</div>

You are very very close:

class User\<ActiveRecord::Base  
has\_many :user\_groups  
has\_many :groups, :through=\>:users  
end

class Group\<ActiveRecord::Base  
has\_many :user\_groups  
has\_many :users, :through=\> :user\_groups  
end

class UserGroup\<ActiveRecord::Base  
belongs\_to :user  
belongs\_to :group  
end

Might I suggest a name change? UserGroup might work better as  
Membership.  
It reads better, and it represents the actual entity you’re trying to  
handle. You can then use that model to manage the relationships  
directly.  
Find that record, delete it, and a user is no longer a member of a  
group.

group = Group.find(15)  
group.memberships.create :user=\>User.find(1) #add to a group  
Membership.create(:user\_id=\>2, :group\_id=\>15) #another way to add to a  
group  
Membership.find\_by\_user\_id\_and\_group\_id(1,15).destroy #delete a user  
from  
a group

Hope that helps!
