简体   繁体   中英

rails has_many vs has_many through?

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

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:

  1. has_and_belongs_to_many
  2. has_many #something through: #joining table

In 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM