Skip to content

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.

“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.”

post.author.name
# 1 query for posts + 1 per post
@posts = Post.limit(20)
# 2 queries
@posts = Post.includes(:author).limit(20)

The detail that separates answers:

  • includes lets Rails choose a second query (preload) or a LEFT OUTER JOIN (eager_load).
  • preload cannot filter on the association; Post.includes(:comments).where(comments: { approved: true }) needs the join, so use eager_load.
  • Detect it with bullet, strict_loading, or by counting queries in a request spec.
  • The same shape appears with count in a loop and with serialisers — load the data in the query, not in the view.

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.”

class Account < ApplicationRecord; end
class SavingsAccount < Account; end # STI: `accounts.type` column
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true # commentable_id + commentable_type
end

STI 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.

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.”

Post.find(1) # the record, raises ActiveRecord::RecordNotFound
Post.find_by(id: 1) # the record or nil
Post.where(id: 1) # a relation; .first gives nil if empty

find 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.

Order.transaction do
order.update!(status: "paid")
Inventory.reserve!(order)
end
  • Any exception rolls back; ActiveRecord::Rollback rolls back silently on purpose.
  • update returns false and does not roll back — update! is required inside a transaction.
  • Pessimistic locking: with_lock or .lock issues SELECT ... FOR UPDATE.
  • Optimistic locking: a lock_version column; a conflicting save raises ActiveRecord::StaleObjectError.
  • Locks hold only inside a transaction, and consistent lock ordering is what prevents deadlocks.

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).

“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.

  • “Rails is magic.” It is Ruby: method_missing, define_method, included hooks, Zeitwerk.
  • “Observers handle callbacks.” Removed from core in Rails 4.
  • “includes always runs two queries.” It does not; eager_load joins.
  • “save raises 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?”