In Active Record, how do where.missing and where.associated find apartments without photos or with photos, and what SQL do they run?
answer
- takes association names, not tables
- missing: LEFT OUTER JOIN plus IS NULL
- associated: INNER JOIN plus IS NOT NULL
- association scope lands in the ON clause
- has_many join can repeat rows
basics
~10 sApartment.where.missing(:photos) left-joins photos and keeps rows where photos.id IS NULL; Apartment.where.associated(:photos) inner-joins photos and keeps rows where photos.id IS NOT NULL. Both take association names and accept several at once.
solid answer
~40 sBoth are `WhereChain` methods that take **association names**. `Apartment.where.missing(:photos)` adds `LEFT OUTER JOIN photos ON photos.apartment_id = apartments.id` and `WHERE photos.id IS NULL`, so only apartments with no photo row survive: the classic "listings needing photos" report in one query. `Apartment.where.associated(:photos)` adds an `INNER JOIN` plus `photos.id IS NOT NULL`, and reuses a `joins` or `left_joins` already on the relation. Because it is a join, an apartment with five photos comes back five times from `where.associated(:photos)`, so add `distinct` when you list them. Several names (`where.missing(:photos, :landlord)`) are ANDed. A scoped association such as `has_many :approved_photos, -> { where(approved: true) }` puts its condition into the join's ON clause, so `where.missing(:approved_photos)` finds apartments with no approved photo. An unknown name raises `ArgumentError`.
code
ruby · 14 linesclass Apartment < ApplicationRecord
has_many :photos
has_many :approved_photos, -> { where(approved: true) }, class_name: "Photo"
belongs_to :landlord
end
# listings still waiting for any photo, cheapest first
Apartment.where(rent: ..1200).where.missing(:photos).order(:rent)
# listings with no approved photo (unapproved uploads do not count)
Apartment.where.missing(:approved_photos)
# listings that have photos, one row each
Apartment.where.associated(:photos).distinctgo deeper
Know that where.missing(:photos) finds records with no associated rows and where.associated(:photos) finds those with at least one.
Describe the SQL: LEFT OUTER JOIN with IS NULL versus INNER JOIN with IS NOT NULL, and why the inner join repeats has_many parents.
Use scoped associations to keep extra conditions in the ON clause, prefer missing over NOT IN subqueries on nullable keys, and handle duplicates before pagination.
Encourage existence filters expressed through associations so reports stay correct as the schema evolves, and make sure the joined foreign keys are indexed.
## The question they answer "Which listings have no photos yet?" and "which listings have at least one photo?" are existence questions about an association. Before these helpers, the idiom was `Apartment.left_joins(:photos).where(photos: { id: nil })`. `where.missing` and `where.associated` name the intent directly and generate the same kind of SQL from the association's reflection. ## where.missing ```ruby Apartment.where.missing(:photos) # SELECT apartments.* FROM apartments # LEFT OUTER JOIN photos ON photos.apartment_id = apartments.id # WHERE photos.id IS NULL ``` How it works: 1. Rails looks up the association by name on the model and raises `ArgumentError` ("An association named `:pictures` does not exist on the model `Apartment`.") if there is none. 2. It adds a **LEFT OUTER JOIN**, so every apartment appears at least once, with NULL photo columns when nothing matched. 3. It filters on the associated table's **primary key IS NULL**, which is only true for the padded, unmatched rows. Because unmatched apartments appear exactly once, `where.missing` on a `has_many` does not duplicate rows. ## where.associated ```ruby Apartment.where.associated(:photos) # SELECT apartments.* FROM apartments # INNER JOIN photos ON photos.apartment_id = apartments.id # WHERE photos.id IS NOT NULL ``` - It uses an **INNER JOIN**, unless the relation already has `joins(:photos)` or `left_joins(:photos)` for that association, in which case it reuses that join. - On a `has_many`, each apartment comes back **once per photo**. For a list of apartments, add `.distinct`; if you only need a yes/no per apartment, a subquery or `exists?` is lighter. - On a `belongs_to`, `Apartment.where.associated(:landlord)` keeps apartments whose landlord row actually exists. ## Details that come up in interviews | Situation | Behaviour | |---|---| | several names: `where.missing(:photos, :floor_plan)` | one join per name, conditions ANDed: missing **both** | | scoped association `has_many :approved_photos, -> { where(approved: true) }, class_name: "Photo"` | the scope goes into the ON clause, so `missing` finds apartments with no **approved** photo | | `belongs_to :landlord` with `where.missing(:landlord)` | finds both `landlord_id IS NULL` rows and orphans whose landlord was deleted | | combined with other filters | ordinary chaining: `Apartment.where(rent: ..1200).where.missing(:photos)` | The scoped-association row is the subtle one. If you wrote `left_joins(:photos).where(photos: { approved: true, id: nil })` by hand, the `approved` condition would land in WHERE and contradict `id IS NULL`, returning nothing. Putting the condition on the association keeps it in the join, where it belongs. ## How Rails builds the condition Under the hood both methods follow the same steps for each name you pass: 1. Find the association's **reflection** on the model. 2. Add the join: `left_outer_joins!` for `missing`, `joins!` for `associated` (unless an equivalent join is already present). 3. Build a hash condition on the associated table's **primary key** with a `nil` value, so `missing` gets `IS NULL` and `associated` gets the inverted `IS NOT NULL`. A model with a composite primary key gets one such predicate per key column. Because the condition is an ordinary hash condition, it composes with everything else in the chain, including `or` between relations that share the same joins. ## Choosing between them and the alternatives - **where.missing vs `where.not(id: Photo.select(:apartment_id))`**: the NOT IN form returns no rows at all if any `apartment_id` is NULL, while the LEFT JOIN form has no such trap. - **where.associated vs `where(id: Photo.select(:apartment_id))`**: the `IN (subquery)` form returns each apartment once without `distinct`, which can be simpler for listings; `where.associated` reads better and composes with other join-based filters. - **Counting**: if the question becomes "apartments with fewer than three photos", you need grouping and `having`, which is a calculation question, not an existence one. ## Practical guidance - Use `where.missing` for data-quality reports: listings without photos, users without a profile, orders without a payment. - Index the foreign key (`photos.apartment_id`) so the join is cheap. - Remember the duplicate rows from `where.associated` on a `has_many` before paginating or counting.
- Why does Apartment.where.associated(:photos).count return more than the number of apartments with photos?`where.associated` uses an INNER JOIN, so an apartment with four photos produces four joined rows and is counted four times. Add `distinct` to the relation, or express the condition as `where(id: Photo.select(:apartment_id))`, which returns each apartment once.
- How would you find apartments with no approved photo, when unapproved photos exist?Declare a scoped association, `has_many :approved_photos, -> { where(approved: true) }, class_name: "Photo"`, and call `Apartment.where.missing(:approved_photos)`. The scope goes into the join's ON clause, so unapproved photos do not count as a match.
where.missing is a roll call held with the photo album open beside the register: every apartment is called, and the ones with no matching page in the album are the ones you write down. where.associated keeps only the names that do have a page, and writes a name down once for every page it has.
- where.missing takes a table name such as :photos_table
- where.associated returns each apartment once even on a has_many
- where.missing loads all apartments and photos and compares them in Ruby
- where.missing(:photos, :landlord) finds apartments missing either association
- An association's scope is ignored by where.missing