DEV Community

grant-ours
grant-ours

Posted on

1

Many-to-Many Relationships

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

For more on active record associations check out: https://guides.rubyonrails.org/association_basics.html

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay