Reputation: 189
I've read about the relationship identifiers has_many
and has_many through
. What I can't seem to understand is the difference between them. For example, if I had 3 models, Doctors, Appointments and Patients
class Doctor< ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :doctor
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :doctors, through: :appointments
end
Couldn't I just say that Doctor has_many :patients and Patient has_many :doctors and they'd be related? What's the purpose of going through appointments to do this?
thanks
Upvotes: 1
Views: 1823
Reputation: 15917
The only reason to use a 'through' table is when you would like to use some relating data contained in the middle table, in this case the appointment data relating to both doctors and patients.
Also, has_many
expects a related belongs_to
and visa-versa, so you have to use has_and_belongs_to_many
in both models to indicate a many-to-many relationship, and create the appropriate join table to go with it.
Otherwise, yes, you could simply use has_and_belongs_to_many :patients
and has_and_belongs_to_many :doctors
in their respective files.
Pay particular attention to section 2.8 in the Rails Guide. It may take a few read throughs, but once you get it, it will make sense, I promise.
Upvotes: 0
Reputation: 6351
You are right. If you say a doctor has_many :patients
and a patient has_many :doctors
, then they will be related.
However, I think what this tutorial is getting at is many-to-many association.
If the doctor model and the patient model are related by has_many
, then a doctor exclusively owns a patient and a patient owns a doctor. But often, this may not be the case. A doctor can have many patients, and those patients do not have to belong to the doctor exclusively; they might have other doctors.
That's when many-to-many association comes in. In a many-to-many association, an object can have many objects which belong to it but not exclusively. It's just like the association between the doctor model and the patient model.
There are two ways to create a many-to-many association:
has_and_belongs_to_many
has_many
#something through:
#joining tableIn your case, you are using the second way, with the joining table assocation
.
Check out this Railscast on detailed explanation of these two. Also, this this official Rails documentation on associations will be helpful.
Upvotes: 1