Bi-directional self-referential HABTM


#1

Hi,

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?


#2

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.


http://www.5valleys.com/