http://www.aldenta.com/2006/11/10/has_many-through-self-referential-example/
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.
On Jun 24, 10:06 am, Iain Adams
<aca04...-3Ch7lUbXYW61Qrn1Bg8BZw@public.gmane.org>
wrote:> 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
>
> <b>Alliance Table</b>
>
> id | initiator_id | acceptor_id
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---