skip to content

Joins & Relation Merging

joins writes an INNER JOIN, left_joins a LEFT OUTER JOIN, and merge reuses another model's scope across the join. Interviewers ask why has_many joins duplicate rows and when joins beats includes.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In Active Record, what SQL do joins and left_joins generate from association names, and how do you filter on the joined table?

level: juniorimportance: must knowfreq 74%

answer

  1. association names, not table names
  2. joins writes INNER JOIN
  3. left_joins writes LEFT OUTER JOIN
  4. nested hash for multi-level joins
  5. where(appointments: { ... }) after the join

basics

~20 s

joins(:appointments) adds an INNER JOIN built from the association, so only doctors with appointments remain; left_joins(:appointments) adds a LEFT OUTER JOIN and keeps every doctor. Filter on the joined table with where(appointments: { starts_at: range }).

solid answer

~40 s

`joins` takes association names and builds the ON clause from the association's keys: `Doctor.joins(:appointments)` gives `INNER JOIN appointments ON appointments.doctor_id = doctors.id`, so doctors without appointments drop out. `left_joins` (alias of `left_outer_joins`) gives a `LEFT OUTER JOIN`, so every doctor stays, with NULL appointment columns when nothing matches. Several names join several tables (`joins(:appointments, :department)`), and a nested hash walks further (`joins(appointments: :patient)`). `joins` also accepts a raw SQL string for joins no association describes, while `left_joins` accepts only association names. To filter on the joined table, use a nested hash keyed by its name, `where(appointments: { starts_at: Time.current.all_week })`, or a string such as `where("appointments.status = ?", "confirmed")`. Either way the result is still `Doctor` objects; the joined columns are only used for filtering and sorting unless you select them.

code

ruby · 15 lines
ruby
class Doctor < ApplicationRecord
  belongs_to :department
  has_many :appointments
end

class Appointment < ApplicationRecord
  belongs_to :doctor
  belongs_to :patient
end

# doctors with a confirmed appointment this week, for pediatric patients
Doctor
  .joins(appointments: :patient)
  .where(appointments: { status: "confirmed", starts_at: Time.current.all_week })
  .where(patients: { pediatric: true })

go deeper

for a junior

Know that joins(:assoc) is an INNER JOIN that drops records without matches, left_joins keeps them, and where(table: { ... }) filters on the joined table.

for a middle

Explain the argument shapes (symbols, nested hashes, strings), why left_joins rejects strings, and that joins filters without loading the association.

for a senior

Choose join types by whether the related row is required, qualify every string column, and read to_sql before multi-level joins reach production.

for a principal

Keep joins expressed through associations so schema changes flow through reflections, and reserve hand-written join strings for cases you document.

## Joining through associations In a clinic scheduler, `Doctor has_many :appointments` and `Appointment belongs_to :doctor, :patient`. Instead of writing join conditions, you pass the **association name** and Active Record builds the `ON` clause from the reflection's foreign and primary keys: ```ruby Doctor.joins(:appointments) # SELECT doctors.* FROM doctors # INNER JOIN appointments ON appointments.doctor_id = doctors.id Doctor.left_joins(:appointments) # SELECT doctors.* FROM doctors # LEFT OUTER JOIN appointments ON appointments.doctor_id = doctors.id ``` | Method | SQL join | Doctors with no appointments | |---|---|---| | `joins(:appointments)` | `INNER JOIN` | removed | | `left_joins(:appointments)` / `left_outer_joins` | `LEFT OUTER JOIN` | kept, appointment columns NULL | ## Shapes of the argument `joins` accepts several argument shapes: 1. **One or more symbols**: `joins(:appointments, :department)` adds one join per association, all from `doctors`. 2. **A nested hash** to walk further: `joins(appointments: :patient)` joins `appointments` from `doctors`, then `patients` from `appointments`. Hashes and arrays nest: `joins(appointments: [:patient, :room])`. 3. **A SQL string** for joins no association describes: `joins("INNER JOIN rotas ON rotas.doctor_id = doctors.id AND rotas.on_call")`. The string is used verbatim. `left_joins` accepts only association names (symbols, hashes, arrays). Passing it a string raises `ArgumentError` ("only Hash, Symbol and Array are allowed") when the query is built; for a custom outer join, write the whole clause as a string in `joins("LEFT JOIN ...")`. An association's own scope, such as `has_many :confirmed_appointments, -> { where(status: "confirmed") }, class_name: "Appointment"`, is added to the join's `ON` clause when you join it. ## Filtering on the joined table After the join, conditions can mention the joined table: - **Nested hash**: `where(appointments: { starts_at: Time.current.all_week })` becomes `appointments.starts_at BETWEEN ... AND ...`. The key is the table name; Rails also accepts the association name and then aliases the joined table to it. - **Dotted key**: `where("appointments.status" => "confirmed")`. - **String with placeholders**: `where("appointments.starts_at < ?", 1.hour.from_now)`; always qualify columns with the table name, because both tables may have `id`, `created_at` or `status`. - **Another model's scope**: `merge(Appointment.confirmed)`, which reuses a scope instead of restating it. ## Joining the same table twice An appointment can point at two doctors, `belongs_to :doctor` and `belongs_to :referring_doctor, class_name: "Doctor"`. Joining both needs two copies of `doctors`, and Active Record aliases the second: ```ruby Appointment.joins(:doctor, :referring_doctor) # INNER JOIN doctors ON doctors.id = appointments.doctor_id # INNER JOIN doctors referring_doctors_appointments # ON referring_doctors_appointments.id = appointments.referring_doctor_id ``` The alias is built from the association's plural name and the parent table. Rather than hard-coding it in strings, filter with the **association name** as the hash key, `where(referring_doctor: { specialty: "cardiology" })`; Rails then aliases that join to `referring_doctor` and the condition follows it. ## What you get back The SELECT list is still `doctors.*`, so you get `Doctor` objects. The joined rows are used to **filter and sort**, nothing more: - `doctor.appointments` afterwards runs its own query; the join did not load the association. - To read a joined column without loading the association, select it: `Doctor.joins(:appointments).select("doctors.*, appointments.starts_at AS next_start")` exposes `next_start` on each doctor. - With a `has_many` join, a doctor appears once per matching appointment; deduplicating is its own question. ## Practical rules - Use `joins` when the condition **requires** a related row (doctors with a confirmed appointment this week). - Use `left_joins` when related rows are optional, typically for counting or sorting by something that may be missing. - Prefer association names over string joins: they follow foreign-key changes, apply association scopes and handle table aliasing for you. - Check `to_sql` whenever a join chain grows past two levels.

  • How do you add a custom LEFT JOIN that no association describes?
    Write it as a string in `joins`: `Doctor.joins("LEFT JOIN rotas ON rotas.doctor_id = doctors.id AND rotas.week = 41")`. `left_joins` only accepts association names and raises `ArgumentError` for a string. If the ON clause needs user input, sanitize it first rather than interpolating.
  • After Doctor.joins(:appointments), does doctor.appointments use the joined rows?
    No. `joins` only shapes the SQL used to filter doctors; it loads no `Appointment` objects. Calling `doctor.appointments` runs a new query per doctor. If you need the association loaded, use the eager-loading methods; if you need one value, `select` it from the join.
  • How would you join a doctor's department and its hospital in one call?
    Use a nested hash: `Doctor.joins(department: :hospital)`, which joins `departments` from `doctors` and then `hospitals` from `departments`. Combine shapes freely, for example `joins(:appointments, department: :hospital)` for one direct and one two-level join.

  • joins loads the associated records so doctor.appointments needs no query
  • joins(:appointments) keeps doctors that have no appointments
  • left_joins accepts a raw SQL string like joins does
  • joins takes the table name, not the association name
  • where(starts_at: range) after joins filters appointments.starts_at
open as a page

In Active Record, why does Doctor.joins(:appointments).where(appointments: { starts_at: week }) list a doctor several times, and how do you return each doctor once?

level: middleimportance: must knowfreq 62%

basics

~10 s

An INNER JOIN produces one row per matching appointment, and Active Record builds one Doctor object per row. Add .distinct, or filter with where(id: Appointment.where(...).select(:doctor_id)) so the doctors table is never multiplied.

open as a page

In Active Record, when is joins the right choice over includes, and what happens if a view reads doctor.appointments after a joins query?

level: middleimportance: should knowfreq 55%

basics

~20 s

Use joins when appointments only decide which doctors come back or how they sort; it loads no Appointment objects. Reading doctor.appointments afterwards runs one more query per doctor, which is when includes is the right call.

open as a page

In Active Record, how does merge let Doctor.joins(:appointments) reuse an Appointment scope, and what can go wrong when you merge?

level: middleimportance: should knowfreq 45%

basics

~10 s

Doctor.joins(:appointments).merge(Appointment.confirmed) copies the Appointment scope's conditions, still bound to the appointments table, into the doctor query. The join must already be there, and on the same column merge's conditions replace yours.

open as a page

In Active Record, why does Doctor.left_joins(:appointments).where(appointments: { starts_at: week }) drop doctors with no appointments, and how do you keep them?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The LEFT OUTER JOIN keeps doctors with NULL appointment columns, but the WHERE on appointments.starts_at then rejects those NULL rows, so the query behaves like an inner join. Put the date condition in the ON clause, for example through a scoped association.

open as a page