Top Ruby on Rails Interview Questions
Ruby on Rails is one of the most popular web development frameworks, known for its efficiency, scalability, and developer-friendly syntax. Whether you’re a beginner or an experienced developer preparing for a job interview, mastering Rails concepts is crucial.
In this guide, we’ve compiled the top 100 Ruby on Rails interview questions with detailed answers and real-world examples. These questions cover ActiveRecord, MVC architecture, routing, caching, background jobs, API development, security, performance optimization, and more. By the end of this post, you’ll be well-prepared to tackle any Rails-related interview confidently.
Let’s dive in! 🚀
1. What is Ruby on Rails?
Answer:
Ruby on Rails (Rails) is a web application framework written in Ruby. It follows the Model-View-Controller (MVC) pattern and emphasizes convention over configuration (CoC) and Don’t Repeat Yourself (DRY) principles.
Example:
# Simple Rails Controller
class UsersController < ApplicationController
def index
@users = User.all
end
end
2. What is MVC in Rails?
Answer:
MVC stands for Model, View, Controller:
- Model: Handles database logic (ActiveRecord).
- View: Displays data (ERB templates).
- Controller: Manages requests & responses.
3. What is Active Record in Rails?
Answer:
Active Record is the ORM (Object Relational Mapping) layer in Rails that simplifies database interactions.
Example:
class User < ApplicationRecord
end
# Fetch all users
User.all
4. What are migrations in Rails?
Answer:
Migrations allow database schema changes using Ruby instead of raw SQL.
Example:
rails generate migration AddEmailToUsers email:string
5. What is the difference between delete
and destroy
in Rails?
Answer:
delete
: Removes a record without callbacks.destroy
: Removes a record and runs callbacks.
Example:
user = User.find(1)
user.delete # No callbacks
user.destroy # Runs callbacks
6. What is the Rails Asset Pipeline?
Answer:
It compiles and serves assets (CSS, JS) efficiently.
7. What are Strong Parameters in Rails?
Answer:
They prevent mass-assignment vulnerabilities by allowing only permitted attributes.
Example:
params.require(:user).permit(:name, :email)
8. Explain the difference between has_one
and belongs_to
.
Answer:
has_one
: A parent has one child.belongs_to
: A child belongs to a parent.
Example:
class User < ApplicationRecord
has_one :profile
end
class Profile < ApplicationRecord
belongs_to :user
end
9. What are Callbacks in Rails?
Answer:
Callbacks are lifecycle methods that run at certain stages.
Example:
class User < ApplicationRecord
before_save :normalize_name
def normalize_name
self.name = name.downcase
end
end
10. What is render
vs. redirect_to
in Rails?
Answer:
render
: Renders a view.redirect_to
: Redirects to another URL.
Example:
render 'new' # Renders new.html.erb
redirect_to users_path # Redirects to index
11. What is the difference between .new
and .create
in Rails?
Answer:
.new
: Instantiates an object without saving..create
: Instantiates and saves in one step.
Example:
user = User.new(name: "John") # Not saved
user.save
user = User.create(name: "John") # Saved
12. How does Rails handle sessions and cookies?
Answer:
- Sessions store data across requests.
- Cookies store data in the user’s browser.
Example:
session[:user_id] = 1
cookies[:username] = "john"
13. What is CSRF protection in Rails?
Answer:
Rails includes Cross-Site Request Forgery (CSRF) protection using protect_from_forgery
.
14. How to handle background jobs in Rails?
Answer:
Use Active Job with Sidekiq or Delayed Job.
Example:
class SendEmailJob < ApplicationJob
queue_as :default
def perform(user)
UserMailer.welcome_email(user).deliver_now
end
end
15. What is the purpose of config/routes.rb
?
Answer:
It defines application routes.
Example:
Rails.application.routes.draw do
resources :users
end
16. How to use concerns in Rails?
Answer:
Concerns allow reusing code across models or controllers.
Example:
module Taggable
extend ActiveSupport::Concern
included do
has_many :tags
end
end
class Post < ApplicationRecord
include Taggable
end
17. What are scopes in Rails?
Answer:
Scopes define reusable queries.
Example:
class User < ApplicationRecord
scope :active, -> { where(active: true) }
end
User.active # Fetch active users
18. Explain has_many :through
association.
Answer:
It connects models through a join table.
Example:
class Doctor < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :doctor
belongs_to :patient
end
19. What is Polymorphic Association in Rails?
Answer:
It allows a model to belong to multiple other models.
Example:
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
class Video < ApplicationRecord
has_many :comments, as: :commentable
end
20. What is the difference between pluck
and select
?
Answer:
pluck
: Fetches specific column values.select
: Returns objects with attributes.
Example:
User.pluck(:name) # Returns array of names
User.select(:name) # Returns ActiveRecord objects
21. What is dependent: :destroy
in Rails?
Answer:
It ensures that associated records are deleted when the parent is deleted.
Example:
class User < ApplicationRecord
has_many :posts, dependent: :destroy
end
When a User
is deleted, all its posts
will be deleted too.
22. What is before_action
in Rails?
Answer:
It runs a method before specific controller actions.
Example:
class UsersController < ApplicationController
before_action :authenticate_user, only: [:edit, :update]
def authenticate_user
redirect_to login_path unless logged_in?
end
end
23. What is has_secure_password
in Rails?
Answer:
It provides authentication features using bcrypt.
Example:
class User < ApplicationRecord
has_secure_password
end
It automatically adds password hashing and authentication.
24. How does Rails handle time zones?
Answer:
Rails uses config.time_zone
to manage time zones.
Example:
config.time_zone = "Eastern Time (US & Canada)"
Time.zone.now
25. What is flash
in Rails?
Answer:flash
is used to show temporary messages between requests.
Example:
flash[:notice] = "User created successfully"
redirect_to users_path
26. What is the difference between symbol
and string
in Ruby?
Answer:
- Symbols (
:name
) are immutable and memory-efficient. - Strings (
"name"
) are mutable.
Example:
:name.object_id == :name.object_id # true
"hello".object_id == "hello".object_id # false
27. What are helpers
in Rails?
Answer:
Helpers are methods used in views to keep logic out of templates.
Example:
module UsersHelper
def full_name(user)
"#{user.first_name} #{user.last_name}"
end
end
28. What is a Concern
in Rails?
Answer:
Concerns are modules that add shared behavior to models or controllers.
Example:
module Archivable
extend ActiveSupport::Concern
included do
scope :archived, -> { where(archived: true) }
end
end
29. What is enum
in Rails?
Answer:enum
defines a set of possible values for an attribute.
Example:
class User < ApplicationRecord
enum role: { admin: 0, user: 1, guest: 2 }
end
30. What is the difference between map
, each
, and collect
in Ruby?
Answer:
each
: Iterates but does not modify the array.map
/collect
: Returns a new array with modified elements.
Example:
[1, 2, 3].map { |n| n * 2 } # [2, 4, 6]
31. What is the difference between find
and where
in Rails?
Answer:
find
: Fetches a single record by primary key.where
: Returns an ActiveRecord relation (can be further chained).
Example:
User.find(1) # Returns a single user
User.where(name: "John") # Returns a relation (array-like)
32. What is the scope
method in Rails?
Answer:
Scopes define reusable queries.
Example:
class User < ApplicationRecord
scope :active, -> { where(active: true) }
end
33. What is joins
in Rails?
Answer:joins
performs SQL joins between tables.
Example:
User.joins(:posts).where(posts: { published: true })
34. What is includes
in Rails?
Answer:includes
preloads associations to avoid N+1 queries.
Example:
User.includes(:posts).each { |user| puts user.posts.count }
35. What is eager_load
vs preload
in Rails?
Answer:
eager_load
: UsesLEFT OUTER JOIN
.preload
: Runs separate queries.
Example:
User.eager_load(:posts) # Uses JOIN
User.preload(:posts) # Uses separate queries
36. What is the difference between any?
, present?
, blank?
, and empty?
in Rails?
Answer:
empty?
→ Checks if a collection is empty.blank?
→ Checks if a value isnil
or empty.present?
→ Opposite ofblank?
.any?
→ Checks if an enumerable has at least one item.
37. What is a Rails API-only application?
Answer:
A Rails application without views, used for APIs.
Command:
rails new my_api --api
38. What is the difference between to_s
, to_i
, and to_sym
?
Answer:
to_s
: Converts to string.to_i
: Converts to integer.to_sym
: Converts to symbol.
Example:
"10".to_i # 10
:hello.to_s # "hello"
39. How to set environment variables in Rails?
Answer:
Use the dotenv
gem or Rails credentials.
Example:
ENV['API_KEY']
40. What is nested attributes
in Rails?
Answer:
Allows saving related records via a parent model.
Example:
class User < ApplicationRecord
has_one :profile
accepts_nested_attributes_for :profile
end
41. What is the difference between update
and update_attribute
?
Answer:
update
: Updates multiple attributes and runs validations.update_attribute
: Updates a single attribute but skips validations.
Example:
user.update(name: "John", email: "john@example.com") # Runs validations
user.update_attribute(:name, "Mike") # Skips validations
42. What is update_columns
in Rails?
Answer:update_columns
updates multiple attributes without callbacks or validations.
Example:
user.update_columns(name: "Mike", email: "mike@example.com")
43. What is after_commit
in Rails?
Answer:after_commit
runs a callback only after the database transaction is committed.
Example:
class User < ApplicationRecord
after_commit :send_welcome_email, on: :create
def send_welcome_email
UserMailer.welcome_email(self).deliver_later
end
end
44. What is pluck
in Rails?
Answer:pluck
directly retrieves specific column values from the database as an array.
Example:
User.pluck(:name) # => ["John", "Jane"]
45. What is default_scope
in Rails?
Answer:default_scope
applies a default condition to all queries.
Example:
class User < ApplicationRecord
default_scope { where(active: true) }
end
46. What is counter_cache
in Rails?
Answer:
It stores the count of associated records in a separate column.
Example:
class Post < ApplicationRecord
has_many :comments, counter_cache: true
end
This reduces database queries for counting.
47. What is the difference between has_many :through
and has_and_belongs_to_many
?
Answer:
has_many :through
: Uses a join model.has_and_belongs_to_many (HABTM)
: Direct many-to-many association without a join model.
Example:
class Doctor < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
48. How does Rails handle CORS?
Answer:
Using the rack-cors
gem to allow cross-origin requests.
Example (config/initializers/cors.rb):
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :options]
end
end
49. What is optimistic locking
in Rails?
Answer:
It prevents concurrent updates from overriding each other.
Example:
class Product < ApplicationRecord
attribute :lock_version, :integer
end
50. What is pessimistic locking
in Rails?
Answer:
It locks a database row while being updated.
Example:
product = Product.lock.find(1)
51. What is delegate
in Rails?
Answer:delegate
forwards method calls to another object.
Example:
class User < ApplicationRecord
belongs_to :profile
delegate :bio, to: :profile
end
Now user.bio
will return profile.bio
.
52. What is transaction
in Rails?
Answer:
A transaction
ensures multiple database operations are atomic.
Example:
ActiveRecord::Base.transaction do
user.update!(balance: user.balance - 100)
account.update!(balance: account.balance + 100)
end
53. What is touch
in Rails?
Answer:touch
updates the updated_at
timestamp of a record.
Example:
user.touch # Updates updated_at
54. What is the difference between destroy_all
and delete_all
?
Answer:
destroy_all
: Runs callbacks and deletes records.delete_all
: Directly deletes records from the database.
Example:
User.destroy_all # Triggers callbacks
User.delete_all # Does not trigger callbacks
55. How to implement soft delete in Rails?
Answer:
Using the paranoia
gem or adding a deleted_at
column.
Example:
class User < ApplicationRecord
def soft_delete
update(deleted_at: Time.current)
end
end
56. What is ActiveStorage
in Rails?
Answer:
It handles file uploads natively in Rails.
Example:
class User < ApplicationRecord
has_one_attached :avatar
end
57. What is the difference between present?
, blank?
, and nil?
?
Answer:
nil?
→ True if the object isnil
.blank?
→ True ifnil
or empty (""
).present?
→ Opposite ofblank?
.
Example:
"".blank? # true
"Hello".present? # true
58. How do you cache data in Rails?
Answer:
Using Rails.cache
.
Example:
Rails.cache.fetch("user_#{user.id}") { user.name }
59. How to use enum
with a default value in Rails?
Answer:
Use default:
in migration.
Example:
class AddRoleToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :role, :integer, default: 0
end
end
60. What is yield
in Ruby?
Answer:yield
passes control to a block.
Example:
def greet
puts "Hello"
yield
puts "Goodbye"
end
greet { puts "How are you?" }
Output:
Hello
How are you?
Goodbye
61. What is Rails.application.config_for
?
Answer:
It loads YAML configuration files from config/settings.yml
.
Example:
settings = Rails.application.config_for(:database)
puts settings["host"]
62. What is turbo
in Rails?
Answer:Turbo
(from Hotwire) speeds up page updates without JavaScript.
Example:
<%= turbo_frame_tag "posts" do %>
<%= render @posts %>
<% end %>
63. What is stimulus.js
in Rails?
Answer:Stimulus.js
is a lightweight JavaScript framework for enhancing Rails views.
Example:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
greet() {
alert("Hello from Stimulus!")
}
}
64. What is prepend_before_action
?
Answer:
Runs a before_action
before others in a controller.
Example:
class ApplicationController < ActionController::Base
prepend_before_action :set_locale
end
65. What is Rails.cache.fetch
?
Answer:
It caches expensive database queries.
Example:
Rails.cache.fetch("users_list", expires_in: 12.hours) do
User.all.to_a
end
66. How do you use has_many :through
with additional attributes?
Answer:
Use a join model with extra fields.
Example:
class Appointment < ApplicationRecord
belongs_to :doctor
belongs_to :patient
end
class Doctor < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
67. How do you enable SQL logging in Rails?
Answer:
Use ActiveRecord::Base.logger
.
Example:
ActiveRecord::Base.logger = Logger.new(STDOUT)
68. What is ActiveSupport::Concern
?
Answer:
A cleaner way to include shared logic in models.
Example:
module Archivable
extend ActiveSupport::Concern
included do
scope :archived, -> { where(archived: true) }
end
end
69. What is ActiveRecord::Relation
?
Answer:
It represents a database query that hasn’t been executed yet.
Example:
users = User.where(active: true) # This is an ActiveRecord::Relation
users.to_a # Executes the query
70. What is ActionCable
in Rails?
Answer:
It enables WebSockets for real-time features like chat.
Example (channels/chat_channel.rb):
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat_#{params[:room]}"
end
end
71. How do you generate a Rails API-only app?
Answer:
Use the --api
flag.
Command:
rails new my_api --api
72. What is rails credentials:edit
?
Answer:
It securely stores API keys and secrets.
Command:
EDITOR=nano rails credentials:edit
73. How do you serve static assets in Rails?
Answer:
Enable config.public_file_server.enabled = true
in production.rb
.
74. What is bundle exec
in Rails?
Answer:
It ensures that commands run using the correct Gemfile dependencies.
Example:
bundle exec rails server
75. What is shallow routing
in Rails?
Answer:
It avoids nesting unnecessary routes.
Example:
resources :posts, shallow: true do
resources :comments
end
76. What is dotenv-rails
?
Answer:
It loads environment variables from .env
files.
Example (.env
file):
API_KEY=abcdef123456
77. How do you force SSL in Rails?
Answer:
Set force_ssl = true
in config/environments/production.rb
.
78. What is self.included(base)
in Ruby modules?
Answer:
It allows executing code when a module is included in a class.
Example:
module Greeting
def self.included(base)
puts "#{base} included Greeting"
end
end
79. How do you create a Rails task?
Answer:
Create a .rake
file inside lib/tasks
.
Example (lib/tasks/hello.rake
):
namespace :greet do
desc "Say hello"
task hello: :environment do
puts "Hello, World!"
end
end
Run it with:
rake greet:hello
80. What is Rails.logger
?
Answer:
It logs messages in log/development.log
.
Example:
Rails.logger.info "This is a log message"
81. What is the difference between map
, collect
, and each
in Ruby?
Answer:
map
andcollect
return a new array after applying the block to each element.each
just iterates without returning a new array.
Example:
numbers = [1, 2, 3]
# map and collect
squares = numbers.map { |n| n * n } # => [1, 4, 9]
# each
numbers.each { |n| puts n * n } # Prints: 1 4 9
82. What is Rails.application.routes.draw
?
Answer:
It defines the routes for a Rails application.
Example (config/routes.rb
):
Rails.application.routes.draw do
resources :users
end
83. How do you rescue exceptions globally in Rails?
Answer:
Use rescue_from
in ApplicationController
.
Example:
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :not_found
def not_found
render json: { error: "Record not found" }, status: :not_found
end
end
84. How to handle background jobs in Rails?
Answer:
Use ActiveJob
with Sidekiq or DelayedJob.
Example:
class SendEmailJob < ApplicationJob
queue_as :default
def perform(user)
UserMailer.welcome_email(user).deliver_now
end
end
Enqueue job:
SendEmailJob.perform_later(user)
85. What is config.middleware.use
in Rails?
Answer:
It adds custom middleware to the Rails request stack.
Example:
Rails.application.config.middleware.use MyCustomMiddleware
86. What is after_initialize
in Rails?
Answer:
It runs code after Rails is fully initialized.
Example (config/initializers/custom.rb
):
Rails.application.config.after_initialize do
puts "Rails has started!"
end
87. How do you debug Rails applications?
Answer:
Use byebug
or pry
.
Example:
def show
byebug
@user = User.find(params[:id])
end
Start the server and trigger the action to pause execution.
88. What is rake db:migrate:status
?
Answer:
It shows the status of all migrations.
Command:
rake db:migrate:status
89. How do you rollback a migration in Rails?
Answer:
Use rails db:rollback
.
Command:
rails db:rollback STEP=1
90. What is the difference between rake
and rails
commands?
Answer:
rake
: Runs tasks without needing Rails booted.rails
: Runs tasks that require Rails booted.
Example:
rake db:migrate # Can also be done using:
rails db:migrate
91. What is rails notes
?
Answer:
It finds TODO
, FIXME
, and OPTIMIZE
comments in your code.
Command:
rails notes
92. What is Rails.application.eager_load!
?
Answer:
It loads all application classes eagerly.
Example:
Rails.application.eager_load!
93. How do you use include
, extend
, and prepend
in Ruby modules?
Answer:
include
: Adds methods as instance methods.extend
: Adds methods as class methods.prepend
: Overrides methods from the beginning of the lookup chain.
Example:
module Greetings
def greet
"Hello!"
end
end
class User
include Greetings # Adds instance method
end
class Admin
extend Greetings # Adds class method
end
user = User.new
puts user.greet # "Hello!"
puts Admin.greet # "Hello!"
94. What is Rails.application.config.active_record.belongs_to_required_by_default
?
Answer:
It forces belongs_to
associations to require presence by default.
Example (config/application.rb
):
Rails.application.config.active_record.belongs_to_required_by_default = false
95. What is foreign_key
in Rails migrations?
Answer:
It enforces referential integrity at the database level.
Example:
add_foreign_key :orders, :users
96. What is up
, down
, and change
in Rails migrations?
Answer:
up
: Runs migration forward.down
: Rolls it back.change
: Runs forward and reverses automatically.
Example:
class AddAgeToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :age, :integer
end
end
97. What is render json:
in Rails?
Answer:
It returns JSON responses in controllers.
Example:
def show
render json: { user: @user }
end
98. What is where.not
in ActiveRecord?
Answer:
It filters records excluding certain conditions.
Example:
User.where.not(role: "admin")
99. How do you preload associations in Rails?
Answer:
Use includes
, joins
, or eager_load
.
Example:
User.includes(:posts).all
100. What is rails g migration
?
Answer:
It generates a migration file.
Command:
rails g migration AddAgeToUsers age:integer
Preparing for a Ruby on Rails interview requires a deep understanding of the framework’s core features, best practices, and real-world applications. This guide has covered 100 essential interview questions, ranging from basic concepts to advanced topics like ActiveRecord associations, caching strategies, background jobs, and API optimizations.
To ace your Rails interview:
✅ Practice coding with hands-on projects.
✅ Understand Rails internals, especially how ActiveRecord, routing, and controllers work.
✅ Stay updated with the latest Rails versions and best practices.
Bookmark this guide and keep revisiting these questions to strengthen your knowledge. Good luck with your interview! 🚀💡