In Active Record, how does merge let Doctor.joins(:appointments) reuse an Appointment scope, and what can go wrong when you merge?
answer
- conditions travel with their table
- you still need the join
- later conditions win on the same column
- unqualified strings become ambiguous
- and intersects, merge overrides
basics
~10 sDoctor.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.
solid answer
~40 s`merge` folds another relation's conditions, order and other values into the receiver. Because hash conditions in `Appointment.confirmed` (`where(status: "confirmed")`) are built against the `appointments` table, merging them into `Doctor.joins(:appointments)` produces `appointments.status = 'confirmed'`, so the scope is reused instead of restated as `where(appointments: { status: ... })`. Three traps: `merge` does not add the join for you, so `Doctor.merge(Appointment.confirmed)` refers to a table that is not in the query and the database raises; a scope written as an unqualified string, such as `where("created_at > ?", 1.week.ago)`, becomes ambiguous once both tables have `created_at`; and where both relations constrain the same column, the merged one **replaces** the receiver's, so `Doctor.where(id: [1, 2]).merge(Doctor.where(id: [2, 3]))` is `id IN (2, 3)`. Use `and` when you want an intersection.
code
ruby · 14 linesclass Appointment < ApplicationRecord
belongs_to :doctor
scope :confirmed, -> { where(status: "confirmed") }
scope :this_week, -> { where(starts_at: Time.current.all_week) }
scope :recent_bad, -> { where("created_at > ?", 1.week.ago) } # unqualified
end
Doctor.joins(:appointments).merge(Appointment.confirmed.this_week).distinct
Doctor.merge(Appointment.confirmed).to_a
# => ActiveRecord::StatementInvalid (appointments is not in the FROM list)
Doctor.joins(:appointments).merge(Appointment.recent_bad).to_a
# => ActiveRecord::StatementInvalid (ambiguous column created_at)go deeper
Know that merge lets a doctor query reuse an Appointment scope, and that you still need joins(:appointments) for it to work.
Explain how merged hash conditions keep their table, why unqualified string scopes break, and that same-column conditions are replaced rather than combined.
Design scopes to be mergeable (hash conditions, no stray order or limit), and choose and over merge when intersecting relations from different sources.
Use mergeable scopes as the shared vocabulary between models, so query rules live with the model that owns the data rather than in callers.
## What merge does `Relation#merge(other)` copies the values of another relation into the current one: WHERE and HAVING conditions, order, limit, joins and more. Its main use across models is **reusing a scope** of the joined model: ```ruby class Appointment < ApplicationRecord scope :confirmed, -> { where(status: "confirmed") } scope :this_week, -> { where(starts_at: Time.current.all_week) } end Doctor.joins(:appointments).merge(Appointment.confirmed.this_week) # SELECT doctors.* FROM doctors # INNER JOIN appointments ON appointments.doctor_id = doctors.id # WHERE appointments.status = 'confirmed' # AND appointments.starts_at BETWEEN ... AND ... ``` The hash conditions inside `Appointment` scopes were built as predicates on the `appointments` table, so they keep pointing there after the merge. The scope's definition lives in one place, and the doctor query does not restate `where(appointments: { status: "confirmed" })`. ## How each part is merged | Part of the merged relation | Result | |---|---| | hash `where` conditions | added; on a column both sides constrain, the merged one replaces the receiver's | | string `where` conditions | added verbatim, so unqualified column names stay unqualified | | `order` | appended, or replacing everything if the merged relation used `reorder` | | association `joins` of another model | converted into joins from that model's table | | `limit`, `offset`, `distinct` and other single values | taken from the merged relation when it sets them | | an Array instead of a relation | intersected in Ruby: `records & other`, loading both | ## Trap 1: merge does not add the join `Doctor.merge(Appointment.confirmed)` puts `appointments.status = 'confirmed'` into a query with no `appointments` table. The database rejects it (for example "missing FROM-clause entry" on PostgreSQL), surfacing as `ActiveRecord::StatementInvalid`. Always pair the merge with the join, `joins(:appointments)` or `left_joins(:appointments)`. ## Trap 2: unqualified string conditions A scope written as `where("created_at > ?", 1.week.ago)` works on `Appointment` alone. Merged into a doctor query, both tables have a `created_at`, and the database reports an ambiguous column. Prefer hash conditions in scopes meant for merging, or qualify the column: `where("appointments.created_at > ?", 1.week.ago)`. ## Trap 3: same-column conditions are replaced The API documentation states it plainly: for conditions that exist in both relations, those from the merged relation take precedence. ```ruby Doctor.where(specialty: "cardiology").merge(Doctor.where(specialty: "neurology")) # WHERE doctors.specialty = 'neurology' ``` That is useful for overriding a default, and surprising when you expected both filters. To combine two relations as an **intersection**, use `and`, which keeps both conditions and requires the relations to be structurally compatible. ## Packaging join plus merge in a scope Because the join and the merge must travel together, the usual pattern is to wrap both in a scope on the parent model: ```ruby class Doctor < ApplicationRecord has_many :appointments scope :booked_this_week, -> { joins(:appointments).merge(Appointment.confirmed.this_week).distinct } end Doctor.booked_this_week.where(specialty: "pediatrics").order(:name) ``` Callers then chain ordinary conditions on doctors without knowing a join is involved, and the definition of "confirmed" still lives in `Appointment`. ## merge versus restating the condition 1. `merge(Appointment.confirmed)` keeps business rules (what "confirmed" means) in the model that owns them. 2. `where(appointments: { status: "confirmed" })` is explicit and fine for one-off filters. 3. Scopes with arguments merge the same way: `merge(Appointment.between(from, to))`. `merge` also accepts a proc, evaluated in the relation's context, for example `merge(-> { joins(:appointments) })`, which is occasionally handy for passing query fragments around. ## Checklist - Join first, then merge. - Keep mergeable scopes on hash conditions or table-qualified strings. - Remember that merged conditions replace same-column ones; reach for `and` to intersect. - Inspect `to_sql` after merging scopes that carry their own order or limit.
- What does Doctor.where(id: [1, 2]).merge(Doctor.where(id: [2, 3])) return, and how do you get the intersection?It returns doctors 2 and 3: the merged relation's condition on `id` replaces the receiver's, as the API docs say. For the intersection, use `Doctor.where(id: [1, 2]).and(Doctor.where(id: [2, 3]))`, which keeps both predicates and yields doctor 2.
- Why should scopes meant for merging use hash conditions?Hash conditions are built as predicates on their own model's table, so after a merge they still read `appointments.starts_at`. A string such as `"starts_at > ?"` is copied verbatim and can become ambiguous or point at the wrong table once another table joins the query.
merge is like attaching a colleague's checklist to your own form: their conditions are kept word for word, but they only make sense if the section they refer to, the joined table, is actually on your form.
- merge adds the joins needed by the merged scope automatically
- merge keeps both conditions when both relations filter the same column
- Unqualified string conditions are rewritten to the merged model's table
- merge and and are interchangeable
- merge with an Array runs a SQL IN query