Ruby on Rails interview questions and answers
Ruby on Rails interview questions test two layers: Ruby itself (blocks, procs and lambdas, modules and mixins, and metaprogramming used with restraint) and the Rails conventions built on it, such as MVC, ActiveRecord associations, the N+1 query and includes, migrations, callbacks, strong parameters, background jobs and caching. Interviewers want to see that you lean on the conventions and also know where they bite in production.
By Evin JohnPublished 7 min read
What Rails interviews usually include
Rails is popular with startups and long-lived product companies that value shipping speed, so many Rails codebases are large and several years old. Interviews reflect that: a Ruby fundamentals screen, a pairing session where you add a feature to a small Rails app with tests, and a conversation about performance, data integrity and how you would refactor a model that has grown too big. Knowing the conventions matters, but explaining the SQL behind an ActiveRecord call matters more.
- Ruby screenBlocks and yield, procs and lambdas, modules, equality, symbols, duck typing. Short answers with a line of irb-style code.
- Pairing in a Rails appAdd an endpoint or a form with validation, an association and a request spec. Interviewers watch how you test and name things.
- Performance and dataSpot the N+1, add the right index, explain a uniqueness race, design a migration for a big table.
- Architecture talkCallbacks versus service objects, concerns, background jobs, caching and how you would split a fat model.
Ruby fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What values are falsy in Ruby? | Truthiness | Only nil and false. Zero, empty strings and empty arrays are truthy, which surprises people coming from JavaScript or Python. |
| Symbol versus string? | Identity | A symbol is an immutable, interned name; the same symbol is always the same object. Strings are mutable values. Symbols suit hash keys and identifiers. |
| ==, eql? and equal?: what is the difference? | Equality | == compares values loosely (1 == 1.0 is true), eql? also compares types and is used by Hash (1.eql?(1.0) is false), equal? checks object identity. |
| What does yield do? | Blocks | It calls the block passed to the current method with the given arguments. block_given? tells you whether one was passed. |
| What is duck typing? | Polymorphism | Code relies on whether an object responds to a method, not on its class. respond_to? and well-named interfaces keep it safe. |
| What are attr_reader, attr_writer and attr_accessor? | Classes | Macros that define getter and setter methods for instance variables. They are ordinary methods called on the class at load time. |
| How does each differ from map? | Enumerable | each iterates for side effects and returns the receiver; map returns a new array of the block's results. |
| What is the GVL and does it matter for Rails? | Concurrency | CRuby's global VM lock lets only one thread run Ruby code at a time, but threads release it during I/O. Web apps are I/O-heavy, so threaded servers like Puma still help. |
square = ->(x) { x * x }
add = proc { |a, b| (a || 0) + (b || 0) }
puts square.call(3) # 9
puts add.call(1) # 1: a proc fills missing arguments with nil
square.call(1, 2) # ArgumentError: a lambda checks arity
def proc_return
pr = proc { return 1 }
pr.call
2
end
def lambda_return
la = -> { return 1 }
la.call
2
end
puts proc_return # 1: return exits the enclosing method
puts lambda_return # 2: return exits only the lambdaModules, mixins and metaprogramming
module Loud
def speak = super.upcase
end
class Dog
def speak = "woof"
end
class Dog
prepend Loud
end
Dog.new.speak # "WOOF"
Dog.ancestors.first(2) # [Loud, Dog]- include, extend or prepend? include adds the module's methods as instance methods after the class in the lookup chain. extend adds them to a single object, often the class itself, as class methods. prepend inserts the module before the class, so its methods run first and can call super.
- What is a Rails concern? A module using ActiveSupport::Concern that bundles included hooks and class methods. Useful for shared behavior such as soft deletion; overused, it scatters a model across many files.
- When is method_missing acceptable? For genuine proxies or dynamic attribute access. Always pair it with respond_to_missing?, call super for unknown names, and prefer define_method when the method names are known up front.
- Why are interviewers wary of metaprogramming? It hides where methods come from, breaks grep and editor navigation, and makes errors harder to trace. The good answer shows you can use it and also explain why you usually choose not to.
- What does monkey patching risk? Changing a core or gem class affects every caller, can conflict with other patches, and breaks on upgrades. Refinements limit the change to files that opt in.
ActiveRecord and the N+1 query
# N+1: one query for the posts, then one per post for its author
Post.order(created_at: :desc).limit(50).each do |post|
puts post.author.name
end
# Fixed: posts, then all needed authors in one more query
Post.includes(:author).order(created_at: :desc).limit(50).each do |post|
puts post.author.name
end| Question | What it tests | What a strong answer shows |
|---|---|---|
| includes, preload or eager_load? | Loading strategies | preload runs a separate query per association. eager_load uses one LEFT OUTER JOIN. includes chooses between them, switching to a join when you filter on the association with references or a hash condition. |
| How do you catch N+1 queries before production? | Tooling | Read the development log, use the Bullet gem, or turn on strict_loading for a model or relation so lazy loads raise. |
| has_many :through versus has_and_belongs_to_many? | Associations | through uses a real join model, which can hold its own columns and validations. HABTM has a bare join table. Most teams choose through so the relationship can grow. |
| Is a uniqueness validation enough? | Data integrity | No. Two requests can pass the check at the same moment and both insert. Add a unique index in the database and handle the resulting error. |
| What are scopes for? | Query composition | Named, chainable query fragments such as published or recent. They return relations, so they stay lazy and combine cleanly. |
| What does counter_cache do? | Performance | Keeps a count column on the parent updated as children are created or destroyed, so listing pages do not run a COUNT per row. |
| How does dependent: :destroy differ from delete_all? | Deletion | destroy loads each child and runs its callbacks; delete_all issues one SQL delete with no callbacks. The first is safer, the second faster. |
| What is a polymorphic association? | Modeling | One model belongs to several kinds of parent through a type and an id column, like comments on posts and on photos. It cannot use a real foreign key constraint. |
Strong parameters, callbacks and migrations
class PostsController < ApplicationController
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post
else
render :new, status: 422
end
end
private
def post_params
params.require(:post).permit(:title, :body, tag_ids: [])
end
end- What problem do strong parameters solve? Mass assignment: without an allowlist, a user could send role or account_id and have it saved. Newer Rails versions also offer params.expect, which is stricter about the shape of the input.
- Why are callbacks a common source of bugs? Logic in after_save runs on every save, including data fixes and tests, and it is easy to forget. Long callback chains make the order of side effects hard to follow.
- after_save or after_commit for sending an email? after_commit. after_save runs inside the transaction, so a job could start before the data is visible, or the email could go out for a record that is rolled back.
- When would you move logic out of a callback? When it is a business process rather than data consistency: charging a card, sending notifications, calling an API. A service object or a job called explicitly is easier to test and reason about.
- How do you write a safe migration on a large table? Add the column as nullable, backfill it in batches as a separate step, add indexes concurrently on PostgreSQL with the DDL transaction disabled, and only then add constraints. Gems such as strong_migrations flag risky operations.
- What is the difference between change and up and down? change is for operations Rails can reverse on its own. Use up and down, or a reversible block, when it cannot, such as a data migration.
Background jobs, caching and security
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why should jobs be idempotent? | Retries | Jobs can run twice after a crash or retry. Design them so a second run does no harm: check state first, use unique keys for payments and emails. |
| What should you pass to a job? | Serialization | IDs or records that Active Job serializes as a GlobalID reference, not large objects. Load fresh data inside perform and handle a record that was deleted meanwhile. |
| Which job backend would you choose? | Infrastructure | Sidekiq with Redis is a long-standing choice; Rails 8 ships Solid Queue, which stores jobs in the database. Pick by throughput needs and what the team already runs. |
| How does Russian doll caching work? | Fragment caching | Nested view fragments are cached with keys based on each record's updated_at. touch: true on the child's belongs_to updates the parent, so only changed fragments re-render. |
| When do you use Rails.cache.fetch? | Low-level caching | To cache an expensive computation or API call with a key and an expiry, ideally with a versioned key so invalidation is a key change. |
| How does Rails protect against SQL injection? | Security | Hash conditions and placeholders such as where("name = ?", name) bind values. Interpolating params into a SQL string is the classic hole. |
| How are XSS and CSRF handled? | Security defaults | ERB escapes output by default, and html_safe or raw opt out. Forms include an authenticity token that the controller verifies on non-GET requests. |
Fictional example
- Our Order model had an after_save callback that sent a confirmation email and another that synced totals to the accounting system. It worked until we wrote a backfill script to fix tax amounts on old orders, and thousands of customers got duplicate confirmations. I moved both side effects out of callbacks into a PlaceOrder service called only from the checkout flow, and switched the remaining notification hook to after_commit so it never fired for rolled-back records. We also added a test that runs the backfill path and asserts no mail is delivered. The model got shorter, and support stopped seeing duplicate emails.
Two-week Ruby on Rails preparation plan
- Days 1 to 3: Ruby. Blocks, procs and lambdas, modules with include, extend and prepend, equality and Enumerable. Run each snippet on this page in irb.
- Days 4 to 6: ActiveRecord. Build a small app with users, posts and comments, read every query in the log, and fix the N+1 queries you find.
- Days 7 to 9: controllers and data integrity: strong parameters, validations backed by indexes, and a migration that backfills in batches.
- Days 10 to 12: Active Job with retries and idempotency, fragment caching with touch, and request specs or system tests.
- Days 13 and 14: a timed pairing mock: add a feature end to end, then refactor one callback into a service object and defend the choice.
Many Rails teams also run PHP or Laravel services, and the two frameworks share a lot of ideas: see PHP and Laravel interview questions. For a JVM-side language with a strong type system and coroutines, compare Kotlin interview questions. The general server-side loop is covered in backend developer interview questions.
Natively, an AI interview assistant for Mac and Windows, keeps a transcript of your mock Rails interviews, handy for checking whether you explained includes or just named it. When you practice, it can read a task or an error from a screenshot, propose a hint or an approach, and with Pro or the free trial take the résumé and job description you add into account. Every session and its notes remain available to review.
Questions people ask
What Ruby on Rails questions are asked in interviews?
Ruby basics such as blocks, procs versus lambdas and modules, then Rails topics: MVC, ActiveRecord associations, the N+1 problem and includes, validations versus database constraints, strong parameters, callbacks, migrations, background jobs and caching.
How do I explain the N+1 problem in a Rails interview?
Say that loading a list and then touching an association per row runs one query per row. Fix it with includes, preload or eager_load, and catch it early with the development log, Bullet or strict_loading.
What Ruby questions come up in Rails developer interviews?
Truthiness, symbols versus strings, equality methods, yield and blocks, procs versus lambdas, include versus extend versus prepend, and when metaprogramming such as method_missing is worth its cost.
What do senior Rails interviews focus on?
Data integrity under concurrency, safe migrations on large tables, moving side effects out of callbacks, idempotent background jobs, caching strategy and finding slow queries in production.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
