Has_and_belongs_to_many linking more than two tables


#1

I have a database with a central lookup table that links about 5
tables together (the examples below are theoretical, I made them up to
illustrate my point):

CREATE TABLE lookup (patient_id int,doctor_id int,nurse_id int);
CREATE TABLE patients (id int, name varchar2(200));
CREATE TABLE doctors (id int, name varchar2(200));
CREATE TABLE nurses (id int, name varchar2(200));

I can throw a has_and_belongs_to_many :patients in doctors.rb and a
has_and_belongs_to_many :doctors in patients.rb but how do I get
nurses in there?

The lookup table I’m using actually has more than three target tables
that it joins. There’s 5 tables. The ActiveRecord docs say “Associates
two classes via an intermediate join table.” for
has_and_belongs_to_many. How do I associate 5 classes via an
intermediate join table?

Thanks,
Geoffeg


#2

haven’t actually tried it, but how about

Doctor
has_and_belongs_to_many :nurses, :join_table => ‘lookup’
has_and_belongs_to_many :patients, :join_table => ‘lookup’

Nurse
has_and_belongs_to_many :doctors, :join_table => ‘lookup’
has_and_belongs_to_many :patients, :join_table => ‘lookup’

Patient
has_and_belongs_to_many :doctors, :join_table => ‘lookup’
has_and_belongs_to_many :nurses, :join_table => ‘lookup’