In Active Record, what SQL do joins and left_joins generate from association names, and how do you filter on the joined table?
answer
- association names, not table names
- joins writes INNER JOIN
- left_joins writes LEFT OUTER JOIN
- nested hash for multi-level joins
- where(appointments: { ... }) after the join
basics
~20 sjoins(: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 linesclass 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
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.
Explain the argument shapes (symbols, nested hashes, strings), why left_joins rejects strings, and that joins filters without loading the association.
Choose join types by whether the related row is required, qualify every string column, and read to_sql before multi-level joins reach production.
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