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 pageshowhide
explore
- Filtering Conditions6 questions
- Ordering, Plucking & Limits5 questions
- Joins & Relation Merging5 questions
- Calculations & Grouping5 questions
- Named Scopes & Laziness5 questions
- Raw SQL & Sanitizing5 questions
- Eager Loading & N+15 questions
- Batches & Bulk Inserts5 questions
questions
page 2 of 2In Active Record, what do the batch options cursor:, order:, start: and finish: do, and what goes wrong when the cursor column changes mid-run?
basics
~20 scursor: 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.
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?
basics
~20 sunique_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.
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?
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.
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?
basics
~20 sStart 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.
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?
basics
~20 sThe 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.
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?
basics
~20 sActive 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).
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?
basics
~20 sKeep 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.
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?
basics
~20 sload_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.
In Rails 8.1, how should code borrow a database connection to run select_all, and why is ActiveRecord::Base.connection discouraged?
basics
~20 sUse 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.
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?
basics
~20 sasync_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.
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?
basics
~20 sfirst 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.
showing 31–41 of 41