Active Record
1. What is an N+1 query, and how do includes, preload and eager_load differ?
An N+1 query loads a collection with one query and then fires one more query per row when the code touches an association. Twenty posts that each call post.author.name in a view produce 21 queries.
preload always runs a separate query per association: one for posts, one for authors with WHERE id IN (...).
eager_load always uses a single LEFT OUTER JOIN, which is required when you filter or sort on the association's columns.
includes picks for you: separate queries by default, a join when the relation references the associated table through references or a hash condition on it.
# N+1: one query for posts, then one per author
Post.limit(20).each { |post| puts post.author.name }
# Two queries
Post.preload(:author).limit(20).each { |post| puts post.author.name }
# One JOIN query, needed because we filter on authors
Post.eager_load(:author).where(authors: { verified: true })
A strong candidate adds prevention, not only cures. strict_loading on a relation, a model or the whole app (config.active_record.strict_loading_by_default) raises or logs when code lazy loads an association, which catches N+1 queries in tests before they reach production.
A weak answer says "always use includes" and misses that eager loading a has_many with thousands of rows per parent trades many small queries for one huge allocation.
2. Find the bug: why does this job sometimes fail with RecordNotFound?
class Order < ApplicationRecord
after_create :send_receipt
private
def send_receipt
ReceiptJob.perform_later(self)
end
end
Order.transaction do
order = Order.create!(params)
order.line_items.create!(items)
end
The callback enqueues the job inside the open transaction. A fast worker can pick it up before COMMIT, look the order up by its GlobalID and find nothing, because other connections cannot see uncommitted rows.
If the line items insert fails, the transaction rolls back and the job runs for an order that never existed.
The fix is to enqueue after the commit, with after_create_commit :send_receipt (or after_commit on: :create).
A strong candidate also mentions that Solid Queue stored in the same database as the app would make the enqueue part of the same transaction, and that the Solid Queue README warns against relying on that, because the guarantee disappears the day the queue moves to its own database, which is the Rails 8 production default.
3. How do you add an index or column to a large PostgreSQL table without downtime?
Build the index concurrently, outside the migration transaction, and add columns in steps that never rewrite or lock the table for long.
class AddIndexOnOrdersCustomerId < ActiveRecord::Migration[8.1]
disable_ddl_transaction!
def change
add_index :orders, :customer_id, algorithm: :concurrently
end
end
Points a senior candidate covers:
CREATE INDEX CONCURRENTLY cannot run inside a transaction, hence disable_ddl_transaction!. If it fails midway it leaves an invalid index that must be dropped before retrying.
- Adding a column with a constant default is a metadata change on PostgreSQL 11 and later, but a volatile default or a backfill in the same migration still touches every row.
- Backfill in batches with
in_batches from a job or a separate script, then add NOT NULL through a validated check constraint.
- Removing a column takes two deploys: first
self.ignored_columns += ["legacy_flag"], then the migration, or running processes with a cached schema will error.
- A
lock_timeout stops a migration from queueing behind a long transaction and blocking every query behind it.
4. Why is a uniqueness validation not enough on its own?
validates :email, uniqueness: true runs a SELECT and then an INSERT, so two requests that arrive together both pass the check and both insert. Only a unique index in the database closes the race.
add_index :users, :email_address, unique: true
# Application code then handles the violation
def self.claim(email)
create_or_find_by!(email_address: email)
end
Keep the validation for the friendly error message and the index for correctness. create_or_find_by tries the insert first and falls back to a lookup when the unique constraint raises ActiveRecord::RecordNotUnique, which is the safer order under concurrency than find_or_create_by.
The same reasoning applies to presence versus NOT NULL and to belongs_to versus a foreign key: a weak answer treats model validations as the data integrity layer, while a strong one treats them as UX on top of constraints.
5. What does this print, and what changed for enum declarations in Rails 8?
class Post < ApplicationRecord
enum :status, { draft: 0, published: 1, archived: 2 }, default: :draft
end
post = Post.new
puts post.status
puts post.draft?
puts Post.published.to_sql
It prints draft, true, and a query with WHERE "posts"."status" = 1. The column stores the integer, the reader returns the string, and the enum defines predicates, bang setters such as post.published! and scopes for each value.
Rails 8.0 removed the old keyword-argument form, enum status: { ... }, so code copied from older tutorials now fails.
Candidates should also know to map values explicitly with a hash rather than an array, because inserting a new value in the middle of an array silently renumbers every later one and corrupts existing rows.
6. When do you use optimistic locking and when pessimistic locking?
Use optimistic locking when conflicts are rare and you can show the user an error, and pessimistic locking when two writers will collide often and the work is short.
- Optimistic: add a
lock_version integer column. Every update includes WHERE lock_version = n and raises ActiveRecord::StaleObjectError when another write got there first. No database lock is held between read and write, which suits forms that stay open for minutes.
- Pessimistic:
account.with_lock { ... } opens a transaction and runs SELECT ... FOR UPDATE, so concurrent writers wait. It suits balance updates, inventory decrements and counters.
account = Account.find(id)
account.with_lock do
raise InsufficientFunds if account.balance < amount
account.update!(balance: account.balance - amount)
end
A weak answer reads the balance, checks it in Ruby and calls update! without any lock.
A strong one also knows the cheapest option for simple counters: an atomic SQL update such as Account.where(id: id).update_counters(balance: -amount) or update_all with a guard condition, which needs no lock in Ruby at all.
7. What are deprecated associations in Rails 8.1, and when would you use them?
Rails 8.1 lets you mark an association with deprecated: true, and Active Record then reports every use of it, including indirect ones through preload, includes and nested attributes.
The Rails 8.1 announcement lists three modes: :warn (the default), :raise and :notify.
class Author < ApplicationRecord
has_many :posts, deprecated: true
has_many :articles
end
The use case is removing an association from a large codebase. Grep finds author.posts, but it misses includes(:posts) built from a variable, serializers that walk associations by name, and accepts_nested_attributes_for.
Running the test suite and production traffic in :warn or :notify mode for a release cycle, then switching tests to :raise, turns a risky deletion into a measured one.
8. How do Active Record encryption and normalizes work?
encrypts encrypts an attribute before it is written and decrypts it on read, with keys from Rails credentials. normalizes, added in Rails 7.1, transforms a value on assignment and when it is used in finder queries.
class User < ApplicationRecord
encrypts :ssn
encrypts :email_address, deterministic: true
normalizes :email_address, with: ->(e) { e.strip.downcase }
end
User.find_by(email_address: " Ana@Example.COM ") # matches "ana@example.com"
The tradeoff a candidate should state: non-deterministic encryption (the default) is stronger, but you cannot query by the column.
Deterministic encryption produces the same ciphertext for the same input, so find_by and unique indexes work, at the cost of revealing which rows share a value.
A strong answer also covers key rotation with previous keys and the fact that encrypted columns need more storage than the plaintext, so a string column limit can overflow.