[Rails] 2 belongs_to to the same parent table

Norman Timmler lists at inlet-media.de
Mon Feb 27 10:23:46 GMT 2006


Am Montag, den 27.02.2006, 09:02 +0100 schrieb agathe agathe:

> I have 2 table: users and buddies
> User: id, name, ...
> Buddy: id, user_id, user_buddy_id, ...
> 
> So if you have 2 users 1,jack and 2,fred and fred is a buddy of jack, 
> there is a Buddy object: id=1, user_id=1, user_buddy_id=2

> I can declare only one belongs_to in Buddy and one has_many in User. And 
> there is conflict if I had the second one (the first one is discarded)
> 
> class User
>   has_many :buddies, :foreign_key => 'user_id'
>  #has_many :buddies, :foreign_key => 'user_buddy_id' # does not work, if 
> added as last, the previous relationship on buddies drops
> end
> 
> class Buddy
>   belongs_to :user, :foreign_key => 'user_id'
>  #belongs_to :user, :foreign_key => 'user_buddy_id' # does not work
> end
> 
> 
> Is there a solution existing in Rails that solves this problem? Or is 
> this design bad anyway?
> I cannot think of any elegant solution. Any advice welcome!!
> 

Here is an interesting discussion about this kind of problem:

http://www.sitepoint.com/forums/showthread.php?t=309718

The solution is to do a self-join on your users table. If you have
further questions let me know.

-- 
Norman Timmler

http://blog.inlet-media.de



More information about the Rails mailing list