Many-to-many relationships
are one of the more common relationships in Rails. When two models have a has_many association to each other, we say they are in a many-to-many relationship.
Here's a many-to-many relationship for example, a doctor can have many patients, and a patient can see many different doctors.
One way to set up a many-to-many relationship with another model is to use the has_many :through
association. In order to do that, we need to create a new join model. For this example we will use Doctor, Patient and Appointment.
class Doctor < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :doctor
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :doctors, through: :appointments
end
But how can we control the associated object when its owner is destroyed?
You can set a dependent to handle these conditions.
For example if I wanted to delete a Doctor I'd need to make sure all of their appointments were taken care of. We'd do that like this.
class Doctor < ApplicationRecord
has_many :appointments, dependent: :destroy
has_many :patients, through: :appointments
end
For more on active record associations check out: https://guides.rubyonrails.org/association_basics.html
Top comments (0)