skip to content

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%

answer

  1. filter versus load
  2. joins instantiates only doctors
  3. association access queries again
  4. select a joined column instead
  5. includes is about the association data

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.

solid answer

~40 s

`joins` exists to **filter and sort** by related rows: `Doctor.joins(:appointments).where(appointments: { starts_at: week })` returns doctors, and no `Appointment` is instantiated. If the view then iterates `doctor.appointments`, each call runs its own query, an N+1 that the join did nothing to prevent, and it returns **all** of that doctor's appointments, not only this week's. `includes` is for the other job: loading associated records so the view can use them. So `joins` beats `includes` when you need related rows only as a condition ("doctors with a confirmed appointment"), as a sort key, or as a single value you can `select` (`select("doctors.*, MIN(appointments.starts_at) AS next_start")` with a `group`). Reach for `includes` when the page renders the associated records. The two can be combined, but how includes picks its strategy is an eager-loading topic.

code

ruby · 17 lines
ruby
week = Time.current.all_week

# filter only: right tool is joins
on_duty = Doctor.joins(:appointments)
                .where(appointments: { starts_at: week })
                .distinct

on_duty.each do |doctor|
  doctor.appointments.to_a  # one query per doctor, and NOT limited to this week
end

# one value per doctor without loading appointments
Doctor.joins(:appointments)
      .where(appointments: { starts_at: week })
      .group("doctors.id")
      .select("doctors.*, MIN(appointments.starts_at) AS next_start")
      .map { |d| [d.name, d.next_start] }

go deeper

for a junior

Remember: joins filters and sorts, includes loads. If the view uses doctor.appointments, joins alone causes a query per doctor.

for a middle

Explain that the join's conditions do not carry over to the association query, and use select with group to read one joined value without loading records.

for a senior

Review list pages for joins followed by association access, decide per page between filtering, aggregating and loading, and surface N+1s with strict_loading.

for a principal

Make 'what does this page render' the deciding question for query shape, and keep filtering and loading as separate, named steps in shared query objects.

## Two different jobs `joins` and `includes` both mention an association, which is why they are confused, but they answer different questions: | | `joins(:appointments)` | `includes(:appointments)` | |---|---|---| | purpose | decide **which doctors** and in what order | load each doctor's **appointments** for use | | SQL | one query with an `INNER JOIN` | separate or joined queries, chosen by Rails | | objects built | `Doctor` only | `Doctor` and `Appointment` | | doctors without appointments | removed | kept | | `doctor.appointments` afterwards | new query per doctor | already loaded | ## What goes wrong when the view reads the association ```ruby @doctors = Doctor.joins(:appointments) .where(appointments: { starts_at: Time.current.all_week }) .distinct ``` ```erb <% @doctors.each do |doctor| %> <%= doctor.name %>: <%= doctor.appointments.size %> <% end %> ``` Two problems: 1. **N+1 queries.** `joins` built no association objects, so each `doctor.appointments` call loads that doctor's appointments separately: one query for the list plus one per doctor. 2. **Wrong data.** The association query is `appointments WHERE doctor_id = ?`, with **no** week filter. The page filtered doctors by this week's appointments, then shows all their appointments ever. The join's condition filtered the parent rows only; it does not carry over to the association. ## When joins is the better tool - **Existence filters**: doctors with at least one confirmed appointment this week, departments with an on-call doctor. - **Sorting by a related column**: `Doctor.joins(:department).order("departments.name")`; with a `belongs_to` join there are no duplicates. - **Reading one value per parent**: select it from the join instead of loading the association. ```ruby Doctor.joins(:appointments) .where(appointments: { starts_at: Time.current.all_week }) .group("doctors.id") .select("doctors.*, MIN(appointments.starts_at) AS next_start") # each doctor responds to next_start; no Appointment objects built ``` - **Lists that never touch the association**: exports, counts and pick lists, where loading appointments would only waste memory. ## When includes is the better tool When the template renders the associated records themselves: names of this week's patients, appointment times per doctor. Loading them up front replaces the N+1 with a fixed number of queries. How `includes` decides between separate queries and one join, and how conditions on an included association also filter the loaded collection, belong to the eager-loading topic. ## Measuring instead of guessing The difference is easy to see in the development log: - The `joins` list followed by association access shows one doctors query and then one `Appointment Load` line per doctor. - An eager-loaded version shows a fixed number of queries whatever the list length. - A `joins` list that never touches the association shows exactly one query and the smallest memory footprint of the three. Count the lines for a page with ten doctors and again with a hundred; a number that grows with the list is the N+1. ## A decision checklist 1. Does the page render associated records? Load them (eager loading). 2. Does it only need to know whether they exist, or sort by them? Use `joins` (or a subquery). 3. Does it need one aggregated value per parent? `joins` with `group` and `select`. 4. Does it need both a filter and the filtered children? Make sure the loaded association is filtered too, not just the parents. Logging query counts in development, or turning on `strict_loading` for the relation, exposes the N+1 in step 1 before it reaches production.

  • Why does doctor.appointments after the joins query show appointments outside this week?
    The association query is built from the association definition alone, `appointments WHERE doctor_id = ?`. The week condition was part of the doctors query and only decided which doctors came back. To show only this week's appointments, load a filtered association or a scoped association such as `has_many :appointments_this_week`.
  • Is joins faster than includes?
    It does less work when you do not need the associated records: one query and no Appointment objects. If the page uses the records, `joins` is slower overall because of the N+1 that follows. Compare by what the page reads, not by the method name.

  • joins and includes are interchangeable ways to load an association
  • After joins, doctor.appointments returns only the appointments matched by the where
  • joins prevents N+1 queries when the view reads the association
  • includes is always faster than joins
  • You need includes to filter doctors by a column of appointments