# Belongs\_to the same table 2 times

**URL:** <https://www.ruby-forum.com/t/belongs-to-the-same-table-2-times/112297>\
**Category:** Rails\
**Created:** [August 17, 2007, 8:03am UTC](https://www.ruby-forum.com/t/belongs-to-the-same-table-2-times/112297 "2007-08-17T08:03:01Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![patrick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/b2d939/32.png) [@patrick](https://www.ruby-forum.com/u/patrick)\
**Post date:** [August 17, 2007, 8:03am UTC](https://www.ruby-forum.com/t/belongs-to-the-same-table-2-times/112297/1 "2007-08-17T08:03:01Z")

</div>

Hi ~

I have the following database design

class Subscription \< ActiveRecord::Base  
belongs\_to :user, :class\_name =\> “User”, :foreign\_key =\>  
‘subscriber\_user\_id’  
belongs\_to :user, :class\_name =\> “User”, :foreign\_key =\>  
‘supplier\_user\_id’  
end

and there existing a user table. How can i access the subscriber and  
supplier in the User object? Because user.subscription may has  
ambiguous for accessing supplier and subscriber

Thank ~  
Patrick

---

<div class="post-metadata">

**Author:** ![patrick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/b2d939/32.png) [@patrick](https://www.ruby-forum.com/u/patrick)\
**Post date:** [August 17, 2007, 8:12am UTC](https://www.ruby-forum.com/t/belongs-to-the-same-table-2-times/112297/2 "2007-08-17T08:12:02Z")

</div>

On 8/17/07, Patrick [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ‘supplier\_user\_id’  
> end
> 
> and there existing a user table. How can i access the subscriber and  
> supplier in the User object? Because user.subscription may has  
> ambiguous for accessing supplier and subscriber
> 
> Thank ~  
> Patrick

Patrick

You can use similar constraints on a has\_many relationship. I think  
this  
should do it for you.

In  
class User \< AR::Base

has\_many :subscribers, :class\_name =\> “Subscription”, :foreign\_key =\>  
“subscriber\_user\_id”  
has\_many :suppliers, :class\_name =\> “Subscription”, :foreign\_key =\>  
“supplier\_user\_id”

end

then  
@user.subscribers  
@user.suppliers

---

<div class="post-metadata">

**Author:** ![patrick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/b2d939/32.png) [@patrick](https://www.ruby-forum.com/u/patrick)\
**Post date:** [August 17, 2007, 10:37am UTC](https://www.ruby-forum.com/t/belongs-to-the-same-table-2-times/112297/3 "2007-08-17T10:37:18Z")

</div>

Thanks, that’s work ~~~
