skip to content

Query Interface

Active Record relations build SQL lazily from chained calls such as where, joins, includes and pluck. Interviewers probe whether you can predict the SQL a chain runs and how many queries it takes.

part ofRuby on Railsread it →
on this pageshow

explore

questions

page 2 of 2

In Active Record, what do the batch options cursor:, order:, start: and finish: do, and what goes wrong when the cursor column changes mid-run?

level: seniorimportance: should knowfreq 30%

basics

~20 s

cursor: picks the unique column set a batch walk sorts and continues by (the primary key by default), order: sets each column's direction, and start: and finish: bound the walk inclusively. A cursor that changes mid-run repeats or skips rows.

open as a page

In Rails 8.1, how do upsert_all's unique_by:, update_only:, on_duplicate: and returning: shape a nightly grocery price sync keyed by sku?

level: seniorimportance: should knowfreq 35%

basics

~20 s

unique_by: names the unique index that decides a conflict (PostgreSQL and SQLite only), update_only: limits which columns are overwritten, on_duplicate: takes custom Arel.sql update SQL, and returning: chooses the columns sent back in the ActiveRecord::Result.

open as a page

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?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Relation#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.

open as a page

When rolling out Active Record's strict_loading across an existing Rails 8.1 app, which levels, modes and violation actions would you use, and in what order?

level: seniorimportance: should knowfreq 34%

basics

~20 s

Start with .strict_loading on list relations, then go app-wide in development and test with the default :raise, and run production on :log with a notification subscriber so a missed load is reported instead of raising.

open as a page

In Active Record, why does Doctor.left_joins(:appointments).where(appointments: { starts_at: week }) drop doctors with no appointments, and how do you keep them?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The LEFT OUTER JOIN keeps doctors with NULL appointment columns, but the WHERE on appointments.starts_at then rejects those NULL rows, so the query behaves like an inner join. Put the date condition in the ON clause, for example through a scoped association.

open as a page

In a Rails chess-club app, why does Member.order(params[:sort]) raise ActiveRecord::UnknownAttributeReference for some inputs, and how should the user-chosen sort be built?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Active Record checks string arguments to order and pluck against a column-shaped pattern and raises UnknownAttributeReference for anything else. Passing the check is not safety, and Arel.sql skips it; map params[:sort] through an allowlist into order(column => direction).

open as a page

In a Rails chess-club app, when would you write the ranking report with find_by_sql rather than a relation using select, with or from, and what do you give up?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Keep a report as a relation while select, with, from or joins can express it, so it stays chainable and preloadable. Use find_by_sql when the SQL reads better whole; it returns a plain Array, so where, includes and scopes no longer apply.

open as a page

In a Rails 8.1 controller, what does calling load_async on several relations buy you, and when does it quietly run each query in the foreground instead?

level: seniorimportance: should knowfreq 28%

basics

~20 s

load_async schedules a relation's SELECT on a background thread pool so independent queries overlap; with the default nil executor, inside a transaction, or on an adapter without concurrent connections, it loads immediately in the calling thread.

open as a page

In Rails 8.1, how should code borrow a database connection to run select_all, and why is ActiveRecord::Base.connection discouraged?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

Use Model.with_connection { |conn| conn.select_all(sql) }, which checks a connection out for the block and returns it to the pool. ActiveRecord::Base.connection is soft-deprecated in Rails 8.1 because it leases the connection for the rest of the request or job.

open as a page

In Rails 8.1, what do async_count and async_sum return, and what must be configured before a dashboard's totals actually run in parallel?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

async_count, async_sum and the other async calculations return an ActiveRecord::Promise whose value blocks for the result; they only run in the background when config.active_record.async_query_executor is set, and the default nil runs them in the foreground.

open as a page

On an Active Record model with random UUID primary keys, why does first return an arbitrary-looking record, and how do implicit_order_column and Rails 8.1 change that?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

first and last sort by the primary key when no order is given, and random UUIDs do not follow creation time. Setting implicit_order_column = "created_at" makes them sort by that column, with the primary key appended as a tiebreaker.

open as a page

showing 31–41 of 41