Rails Interview Questions
Rails interviews are not trivia. The same eight topics come up repeatedly, and each has a shallow answer and a deep one. The shallow answer clears the screen; the deep answer — the one that names the trade-off and the failure mode — is what gets you hired.
The 60-second answer
Section titled “The 60-second answer”“Rails is MVC with convention over configuration, and the two things that bite in production are the ORM and the callbacks. The ORM means every Ruby line is a query you should be able to predict, so N+1s and missing indexes are the performance story. The callbacks mean persistence has side effects, so transactional boundaries are the correctness story. Everything else — routing, controllers, views, jobs, Turbo — follows from those two.”
1. Explain the N+1 problem
Section titled “1. Explain the N+1 problem”# 1 query for posts + 1 per post@posts = Post.limit(20)# 2 queries@posts = Post.includes(:author).limit(20)The detail that separates answers:
includeslets Rails choose a second query (preload) or aLEFT OUTER JOIN(eager_load).preloadcannot filter on the association;Post.includes(:comments).where(comments: { approved: true })needs the join, so useeager_load.- Detect it with
bullet,strict_loading, or by counting queries in a request spec. - The same shape appears with
countin a loop and with serialisers — load the data in the query, not in the view.
2. Callbacks vs observers
Section titled “2. Callbacks vs observers”Callbacks are methods hooked to the Active Record lifecycle (before_save, after_create, after_commit). Observers were a separate class listening to a model from outside; they were removed from core in Rails 4 and now live only in the rails-observers gem. So the real question is callbacks vs service objects:
| Callback | Service object | |
|---|---|---|
| Trigger | Any save, including console and seeds | Explicit call |
| Testability | Requires a save | Plain Ruby |
| Debuggability | Hidden from the call site | Visible |
| Right for | Invariants of the row (normalise, defaults) | Orchestration, external effects |
“I use callbacks for things true of the record however it is saved — slug generation, normalisation, a counter cache. Anything that reaches outside the record — email, payment, indexing, broadcast — goes in a service object or a job, usually from after_commit.”
3. STI vs polymorphic
Section titled “3. STI vs polymorphic”class Account < ApplicationRecord; endclass SavingsAccount < Account; end # STI: `accounts.type` column
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true # commentable_id + commentable_typeendSTI answers “these are the same kind of thing with different behaviour”: one table, Account.all returns every subtype, good when subtypes share columns and bad when they diverge into nullable columns. Polymorphic answers “this attaches to several different kinds of thing”: no foreign key, and a string column that breaks if you rename the class. If you need integrity, use two nullable FKs with a check constraint instead.
4. has_many :through vs habtm
Section titled “4. has_many :through vs habtm”through goes through a real model, so the join can carry data (role, position, created_at), validations and callbacks. habtm uses a bare two-column join table with no model. Choose through almost always — the only case for habtm is a genuinely attribute-free many-to-many, and even then through costs little. The follow-up is “how do you add a column to the join table?”, which with habtm has no answer short of a rewrite.
5. includes, preload, eager_load, references
Section titled “5. includes, preload, eager_load, references”| Method | Queries | Filters on association | Use when |
|---|---|---|---|
includes |
Rails decides | Only with references |
Default choice |
preload |
Always 2 | No | You know no join is needed |
eager_load |
Always 1 (LEFT OUTER JOIN) |
Yes | You filter or order by the association |
references |
Forces the join | Yes | Pairs with includes and a string condition |
“includes is the default; I switch to eager_load when I filter by the association, because preload cannot express that in one query.”
6. find vs find_by vs where
Section titled “6. find vs find_by vs where”Post.find(1) # the record, raises ActiveRecord::RecordNotFoundPost.find_by(id: 1) # the record or nilPost.where(id: 1) # a relation; .first gives nil if emptyfind is for “this must exist” — a missing id should be a 404, and Rails’ default handling turns the exception into one. find_by is for “may not exist” — a lookup, a login attempt. where returns a relation, so it composes. find with an array raises if any id is missing; where silently returns fewer rows.
7. Transactions and locking
Section titled “7. Transactions and locking”Order.transaction do order.update!(status: "paid") Inventory.reserve!(order)end- Any exception rolls back;
ActiveRecord::Rollbackrolls back silently on purpose. updatereturns false and does not roll back —update!is required inside a transaction.- Pessimistic locking:
with_lockor.lockissuesSELECT ... FOR UPDATE. - Optimistic locking: a
lock_versioncolumn; a conflicting save raisesActiveRecord::StaleObjectError. - Locks hold only inside a transaction, and consistent lock ordering is what prevents deadlocks.
8. Caching and background jobs
Section titled “8. Caching and background jobs”Layers, cheapest first: HTTP/CDN, fragment cache, Rails.cache, query cache, counter columns.
<% cache [current_user, @post] do %> ... <% end %>Include invalidation in the answer: fragment keys carry updated_at via cache_key_with_version, and touch on parents busts the right level. Rails 8 defaults to Solid Cache, so Redis is optional.
Must-haves: at-least-once delivery therefore idempotency; arguments must be primitives or GlobalIDs; enqueue after commit; adapters are Sidekiq (Redis), GoodJob (Postgres), Solid Queue (Rails 8 default).
9. Two that come up late
Section titled “9. Two that come up late”“What is a concern?” A module with extend ActiveSupport::Concern, an included do block running class macros in the including class, and class_methods. It shares behaviour, not a boundary — if eleven models include it, they are coupled.
“How does a request become HTML?” Router → controller instance (per request) → before_action chain → action → model → instance variables copied into the view context → template plus layout → response through Rack. render does not stop execution; rendering twice raises DoubleRenderError.
Common traps
Section titled “Common traps”- “Rails is magic.” It is Ruby:
method_missing,define_method,includedhooks, Zeitwerk. - “Observers handle callbacks.” Removed from core in Rails 4.
- “
includesalways runs two queries.” It does not;eager_loadjoins. - “
saveraises on failure.” It returns false;save!raises. - “Rails needs Redis.” Not since Solid Cache/Queue/Cable became defaults.
- Answering with a definition and no failure mode. Every Rails question is really “what breaks?”
Further reading
Section titled “Further reading”- Rails Guides
- Rails API documentation
- Ruby — the language underneath the framework.