# Has\_and\_belongs\_to\_many linking more than two tables

**URL:** <https://www.ruby-forum.com/t/has-and-belongs-to-many-linking-more-than-two-tables/107355>\
**Category:** Rails\
**Created:** [June 20, 2007, 8:58pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-linking-more-than-two-tables/107355 "2007-06-20T20:58:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![geoffeg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/0ea827/32.png) [@geoffeg](https://www.ruby-forum.com/u/geoffeg)\
**Post date:** [June 20, 2007, 8:58pm UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-linking-more-than-two-tables/107355/1 "2007-06-20T20:58:33Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![geoffeg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/0ea827/32.png) [@geoffeg](https://www.ruby-forum.com/u/geoffeg)\
**Post date:** [June 21, 2007, 7:36am UTC](https://www.ruby-forum.com/t/has-and-belongs-to-many-linking-more-than-two-tables/107355/2 "2007-06-21T07:36:21Z")

</div>

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’
