Forum: Ruby on Rails Bi-directional self-referential HABTM

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
jeroen (Guest)
on 2007-07-26 18:37
(Received via mailing list)

I'm having a little trouble figuring out how to make a self-
referential HABTM bi-directional.

I have a Employee class. Each employee can have a couple of bosses,
who are also employees. The employee class has the following HABTM:

has_and_belongs_to_many :bosses, :class_name =>
"Employee", :join_table => "bosses_courses", :association_foreign_key
=> "boss_id", :foreign_key => "employee_id"

Now this works fine.. but only one way. I can get all bosses of an
employee but I can't get all employees of a boss.

In hindsight I think it probaby would have been better to use
a :through relationship for this, but I can't really change the
database schema now.

The solution might be to code something like a subordinate method for
the employee class myself, but I'm not sure how to do that.

Does anyone has any good suggestions?
Jon G. (Guest)
on 2007-07-26 20:42
(Received via mailing list)
jeroen wrote:
> => "boss_id", :foreign_key => "employee_id"
> Does anyone has any good suggestions?

You should just be able to add

has_and_belongs_to_many :employees, :class_name => "Employee",
:join_table => "bosses_courses", :association_foreign_key =>
"employee_id", :foreign_key => "boss_id"

Notice how I just changed the name of the relationship, and swapped the
two keys.  This should give you the "other" direction that you're
looking for.  The :class_name and :association_foreign_key  arguments
are probably not necessary in this one, but in this case I would keep
them just to help clearly document the difference between the two
relationships for myself months down the road.

This topic is locked and can not be replied to.