Single Table HABTM

Hi, all

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

obj1 =
obj2 =

obj1.connections << obj2

>> obj1.connections
=> obj2

>> obj2.connections
=> 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.


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.


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

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 declare 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):
>> friend1.friends
=> friend2

>> friend2.reverse_friends
=> friend1

that is not what i want

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

That’s right.

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 you want. If it doesn’t work, I suggest finding unique names that you like for each association. Either way, please share your findings.