HABTM relationship between 2 of the same class

Hello.

I am trying to figure out the neatest way to do this. So far I have a
class called Member. Now I am trying to organise the relationship
“Alliance”.

This relationship means that 2 Members can become allies and they have
an alliance together. My problem comes when trying to create a) the
table b) the relationships.

I have ended up with the following. But was wondering if anyone could
think of a more elegant way of doing this.

class Member < ActiveRecord::Base

has_many :init_alliances, :foreign_key => ‘initiator_id’, :class_name
=> ‘Alliance’
has_many :accept_alliances, :foreign_key => ‘acceptor_id’, :class_name
=> ‘Alliance’

def allies
return (self.accept_alliances.collect{|a|a.initiator} +
self.init_alliances.collect{|a| a.acceptor}).uniq
end

end

class Alliance < ActiveRecord::Base
belongs_to :initiator, :foreign_key => ‘initiator_id’, :class_name
=> ‘Member’
belongs_to :acceptor, :foreign_key => ‘acceptor_id’, :class_name
=> ‘Member’
end

Alliance Table

id | initiator_id | acceptor_id

That link goes over the “has many through” example. That’s what you
are trying to do. Takes a bit to get used to what’s going on.
Basically you have a friendship model (or alliance in your case) with
a user_id and a friend_id, the friendship model belongs to user and
belongs to friend, :class_name => user. In the user model, a user has
many friendships (or alliances) and has many friends through
alliances.

See the example, and ask more questions if it doesn’t work just right.