Single Table HABTM

Hi, all

I’m looking for a trick how to get something like that:

obj1 =
obj2 =

obj1.connections << obj2

=> obj2

=> obj1


PS: The first solve is to make the third join model, and put them all
necessary has_many + has_many relationship, then give the join model
optional method using transaction etc, so it’s inevitable to have two
identical strings in the join models’ database table (to obj1 and
obj2)…? Or i can write some handler to seek obj1 and obj2 using
‘their own’ foreign keys one by one through each other (two has_many
methods with two different foreign keys)?

This earlier thread might be helpful.


On 01.09.2008, at 23:29, Craig D. wrote:

This earlier thread might be helpful.

Thanks, I saw it! But unfortunately this method makes only “one-way”
association and not vice versa (if i’m not mistaken).
Exactly I need - vice versa associations. I thought the only way to do
it is to have two strings in the database (obj1 to obj2 and obj2 to
obj1). Where is the trick?

Ah. I haven’t done that yet. A Google search for

“many-to-many” “self-referential” rails

turns up some hits that could be useful.


This is similar:

What are you think? I guess, there is no transaction improvements to
be a super nice :slight_smile:

Actually, according to a reply in another thread, you could build on
what I
shared earlier. First, declare the habtm as described before, then
another habtm named as you want and with the foreign_key and
association_foreign_key swapped around.

class User < ActiveRecord::Base
has_and_belongs_to_many :friends,
:class_name => “User”,
:join_table => “users_friends”,
:foreign_key => “user_id”,
:association_foreign_key => “friend_id”
has_and_belongs_to_many :reverse_friends,
:class_name => “User”,
:join_table => “users_friends”,
:foreign_key => “friend_id”,
:association_foreign_key => “user_id”

Does that work?

Not exactly: association methods differ from each other (.friends
and .reverse_friends):

=> friend2

=> friend1

that is not what i want

Ok, thanks, maybe i’ll get something intresting or write it myself )

So you like the result but not the name of the association?

I doubt that you can have two habtm associations with the same name, but
I’ve never tried it. I suggest you try it. If it works, you have what
want. If it doesn’t work, I suggest finding unique names that you like
each association. Either way, please share your findings.


That’s right.