In Active Record, how does Relation#or combine two relations, why does it raise 'must be structurally compatible', and where does its precedence surprise people?
answer
- or takes a relation, not a hash
- may differ only in where or having
- Incompatible values: [:joins]
- shared conditions are factored out
- build both sides from one base
basics
~20 sRelation#or ORs the WHERE clauses of two relations of the same model that differ only in where or having; extra joins or limits on the argument raise ArgumentError. Conditions both sides share stay ANDed outside; the rest is grouped by AND before OR.
solid answer
~40 s`a.or(b)` keeps the predicates `a` and `b` share as plain `AND` conditions and ORs the remainder, so `lyon.where(furnished: true).or(lyon.where(pets_allowed: true))` gives `city = 'Lyon' AND (furnished OR pets_allowed)`. Both sides must be **structurally compatible**: same model, differing only in `where` (or `having` when grouped); give the argument a `joins`, `limit` or `includes` the receiver lacks and Rails raises `ArgumentError` naming the incompatible values, such as `[:joins]`. The precedence trap is a condition that sits on one side only: `Apartment.where(city: "Lyon").where(furnished: true).or(Apartment.where(pets_allowed: true))` is `(city AND furnished) OR pets_allowed`, so pet-friendly flats in every city come back. The fix is to build both sides from a shared base relation. Its siblings: `and` intersects two compatible relations, `rewhere` replaces conditions on named attributes, and `invert_where` negates the entire WHERE clause built so far.
code
ruby · 13 linesbase = Apartment.joins(:building).where(city: "Lyon")
base.where(furnished: true).or(base.where(pets_allowed: true))
# city = 'Lyon' AND (furnished = TRUE OR pets_allowed = TRUE)
Apartment.where(furnished: true)
.or(Apartment.joins(:building).where(buildings: { elevator: true }))
# => ArgumentError: Relation passed to #or must be structurally
# compatible. Incompatible values: [:joins]
# scope :available, -> { where(available: true) }
Apartment.available.rewhere(available: false)
# WHERE available = FALSE (not available = TRUE AND available = FALSE)go deeper
Know that or takes a whole relation, such as Apartment.where(a).or(Apartment.where(b)), and that its result is ANDed with any where you chain afterwards.
Explain how shared predicates are factored out, why a one-sided condition binds only to its branch, and what structurally compatible means.
Build dynamic filters from a shared base so or never meets mismatched joins, read to_sql when branches differ, and keep invert_where out of reusable scopes.
When filters grow many optional OR branches, weigh one composed relation against named queries or a search service that keeps precedence reviewable.
## What or does `Relation#or` takes **another relation**, not a hash, and returns a relation whose WHERE clause is the logical union of both. Passing a hash raises `ArgumentError` ("You have passed Hash object to #or. Pass an ActiveRecord::Relation object instead."). The combination is smarter than plain concatenation: 1. Predicates that appear on **both** sides are kept as ordinary `AND` conditions. 2. The predicates left on each side are ANDed within that side. 3. The two leftovers are joined with `OR` and wrapped in one parenthesised group. ```ruby lyon = Apartment.where(city: "Lyon") lyon.where(furnished: true).or(lyon.where(pets_allowed: true)) # WHERE city = 'Lyon' AND (furnished = TRUE OR pets_allowed = TRUE) ``` ## The precedence trap When a condition is on **one side only**, it binds to that side: ```ruby Apartment.where(city: "Lyon").where(furnished: true) .or(Apartment.where(pets_allowed: true)) # WHERE (city = 'Lyon' AND furnished = TRUE OR pets_allowed = TRUE) ``` `AND` binds tighter than `OR`, so this returns furnished Lyon flats **plus every pet-friendly flat in every city**. Developers reading the Ruby left to right expect `city` to apply to both branches. Two fixes: - **Build both sides from a shared base** (`lyon` above) so the common predicate is factored out. - **Apply the shared filter after the or**: `Apartment.where(furnished: true).or(Apartment.where(pets_allowed: true)).where(city: "Lyon")`, since a `where` chained after `or` is ANDed with the whole group. ## Structural compatibility `or` (and `and`) only combine WHERE and HAVING clauses. Every other part of a relation, such as `joins`, `left_outer_joins`, `includes`, `limit`, `offset`, `order`, `select`, `group` or `distinct`, must match between the receiver and the argument, with one tolerance listed below. Rails checks this and raises: ```ruby # ArgumentError: Relation passed to #or must be structurally compatible. # Incompatible values: [:joins] ``` Points worth knowing: - Both relations must scope the **same model**. - The check tolerates the **argument leaving out** a multi-value clause the receiver has (for example the receiver has `order(:rent)` and the argument has none), but not the argument adding one. - `structurally_compatible?(other)` returns the verdict without raising, which helps when composing filters dynamically. - The usual fix is the same as for precedence: derive both sides from one base relation that already carries the joins, so they differ only in `where`. ## and, rewhere and invert_where | Method | What it does | Typical use | |---|---|---| | `and(other)` | intersects two compatible relations' WHERE and HAVING | combining a relation you were handed with your own | | `rewhere(hash)` | removes existing conditions on the named attributes, then adds the new ones | overriding a scope's `available: true` with `available: false` | | `invert_where` | wraps the **entire** WHERE clause built so far in `NOT (...)` | negating a known, local condition | `rewhere` is shorthand for `unscope(where: keys).where(hash)` and only touches the attributes you name, unlike `reorder`, which replaces all ordering. `rewhere(nil)` removes every where condition. `invert_where` deserves a warning. It inverts **everything chained before it**, including conditions from earlier scopes and a `default_scope`. Defining `scope :unavailable, -> { available.invert_where }` looks neat, but `Apartment.where(city: "Lyon").unavailable` becomes `NOT (city = 'Lyon' AND available = TRUE)`, returning flats in other cities. The Rails documentation warns against exactly this pattern. Prefer an explicit `where.not` or a dedicated scope. ## Debugging a combined relation When an `or` returns more rows than expected, print it before reasoning about it: 1. Call `to_sql` on the combined relation and find the outermost parenthesised group. 2. Check which predicates sit **outside** the group (shared by both sides) and which sit **inside** one branch. 3. If the call raised, read the `Incompatible values:` list; it names exactly which relation parts differ, such as `[:joins]` or `[:limit]`. 4. Use `structurally_compatible?` in a dynamic filter builder to decide whether to `or` two pieces or restructure them. ## Practical rules - Write `or` from a shared base relation, never from two unrelated chains. - Read the generated SQL with `to_sql` whenever one side has more conditions than the other. - Keep `invert_where` for short, local relations; never inside a reusable scope. - Reach for `rewhere` when a scope's condition must be replaced rather than contradicted (`available = TRUE AND available = FALSE` returns nothing).
- Why is scope :unavailable, -> { available.invert_where } a bad idea?`invert_where` negates the entire WHERE clause accumulated so far, not just the scope's own condition. Chained after `where(city: "Lyon")`, it yields `NOT (city = 'Lyon' AND available = TRUE)`, so flats in other cities appear. Write `scope :unavailable, -> { where(available: false) }` instead.
- How does rewhere differ from chaining another where on the same column?A second `where(available: false)` is ANDed with the first, giving `available = TRUE AND available = FALSE`, which matches nothing. `rewhere(available: false)` first unscopes conditions on `available`, then adds the new one, leaving other conditions untouched.
- When would you use Relation#and instead of chaining where?When you receive a ready-made relation, for example from a policy or a search object, and must intersect it with another relation of the same model. `mine.and(theirs)` merges both WHERE clauses, under the same structural-compatibility rule as `or`.
- or accepts a hash of conditions like where does
- A where on one side of or applies to both branches
- or merges the argument's joins into the result as long as the model matches
- invert_where only negates the condition passed just before it
- rewhere replaces every where condition on the relation