[Rails] 2 belongs_to to the same parent table

agathe agathe a at battestini.net
Mon Feb 27 08:02:01 GMT 2006


Hello!

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!!

Thnx!!

agathe

-- 
Posted via http://www.ruby-forum.com/.


More information about the Rails mailing list