90 Ruby on Rails Interview Questions

Table of Contents

Introductions

Ruby on Rails is a powerful and popular web development framework that has gained immense popularity due to its simplicity and productivity. If you’re preparing for a Ruby on Rails interview, it’s essential to be well-prepared. In this context, understanding some common interview questions can greatly enhance your chances of success. These questions often focus on key concepts like MVC architecture, database relationships, testing frameworks, and deployment strategies. Additionally, questions regarding routing, migrations, validations, and security measures may arise. By familiarizing yourself with these topics and their related interview questions, you’ll be better equipped to showcase your knowledge and proficiency in Ruby on Rails development.

Basic Questions

1. What is Ruby on Rails?

Ruby on Rails, commonly known as Rails, is an open-source web application framework written in Ruby. It follows the Model-View-Controller (MVC) architectural pattern and aims to simplify the development of web applications by providing conventions for common tasks.

Example:

Ruby
# A simple Rails controller action that renders a view template
class UsersController < ApplicationController
  def index
    @users = User.all
  end
end

2. Explain the difference between Ruby and Ruby on Rails.

RubyRuby on Rails
ProgrammingWeb application development framework
LanguageWritten in Ruby
PurposeGeneral-purpose programming language
FrameworkSpecifically designed for building web apps
SyntaxProvides the basic building blocks for programs
ConventionProvides conventions for web app development

3. What is MVC? How is it implemented in Rails?

MVC stands for Model-View-Controller. It is a software architectural pattern that separates an application into three interconnected components: Model (data and business logic), View (user interface), and Controller (handles user input and updates the model).

In Rails, the MVC pattern is implemented as follows:

  • Model: Represents the data and business logic. It interacts with the database and contains the application’s data model.
  • View: Represents the user interface. It displays data from the model and sends user input to the controller.
  • Controller: Handles user input, interacts with the model to retrieve or update data, and renders the appropriate view.

4. What is ORM? How does it relate to Rails?

ORM stands for Object-Relational Mapping. It is a technique that allows developers to interact with a relational database using object-oriented programming concepts. ORM maps database tables to Ruby classes and table rows to objects.

In Rails, ActiveRecord is the ORM used to perform database operations. It abstracts the database interactions and allows developers to work with Ruby objects instead of writing raw SQL queries.

Example:

Ruby
# User model representing a 'users' table in the database
class User < ApplicationRecord
  validates :name, presence: true
end

# Creating a new user and saving it to the database using ActiveRecord
user = User.new(name: 'John Doe')
user.save

5. What are the principles behind Ruby on Rails?

The principles behind Ruby on Rails, often referred to as “Rails principles” or “Rails philosophy,” include:

  1. Convention over Configuration (CoC): Rails favors sensible conventions over explicit configuration, reducing the need for boilerplate code and making development more straightforward.
  2. Don’t Repeat Yourself (DRY): Encourages the elimination of redundant code to maintain consistency and ease maintenance.
  3. Model-View-Controller (MVC): Separates concerns and promotes modular development.
  4. RESTful Design: Emphasizes the use of RESTful routes and actions for building APIs and web applications.

6. What are migrations, and why are they important?

Migrations in Rails are a way to manage changes to the database schema. They are used to create or modify database tables and keep the database schema in sync with the application’s evolving data model.

Example:

Ruby
# Create a new migration to add a 'email' column to the 'users' table
rails generate migration AddEmailToUsers email:string

# The generated migration file
class AddEmailToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :email, :string
  end
end

# Running the migration to apply the changes to the database
rails db:migrate

7. What is ActiveRecord, and how does it work?

ActiveRecord is the ORM in Rails that facilitates database operations using Ruby classes. It abstracts the database interactions and provides methods for querying and manipulating data.

Example:

Ruby
# User model representing a 'users' table in the database
class User < ApplicationRecord
  validates :name, presence: true
end

# Querying the database using ActiveRecord
users = User.where(age: 25)

8. What is the use of YAML file in Rails?

YAML (YAML Ain’t Markup Language) files in Rails are commonly used for configuration and data serialization purposes. They provide a human-readable format for representing data structures.

Example:

YAML
# config/database.yml
development:
  adapter: postgresql
  database: myapp_development
  username: postgres
  password: secret

test:
  adapter: postgresql
  database: myapp_test
  username: postgres
  password: test_secret

9. What are the different types of associations in Rails? Give a code example.

Rails supports several types of associations to model relationships between database tables. The most common associations are:

  • belongs_to
  • has_one
  • has_many
  • has_many :through
  • has_one :through
  • has_and_belongs_to_many

Example:

Ruby
# User and Post models with a one-to-many association
class User < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :user
end

10. What is the purpose of environments in Rails?

Environments in Rails refer to different runtime configurations for the application. The three standard environments are:

  • Development: Used during local development for debugging and testing.
  • Test: Used when running test cases.
  • Production: The live environment where the application is deployed and used by end-users.

11. What is REST in Rails?

REST (Representational State Transfer) is an architectural style used in web development, particularly for APIs. It defines a set of conventions for structuring routes and actions in a web application.

Example:

Ruby
# Configuring a RESTful route for posts in the 'routes.rb' file
resources :posts

In this example, the resources method generates a set of RESTful routes for CRUD operations on posts, such as index, show, new, create, edit, update, and destroy.

12. What is the difference between a Symbol and a String in Ruby?

SymbolString
Prefixed with a colon (e.g., :name)Enclosed in single or double quotes
ImmutableMutable (can be modified in place)
Memory-efficientConsumes more memory
Used for identifiers and keysUsed for representing textual data
Commonly used as keys in hashesNot commonly used as hash keys

13. What are some advantages of using Rails for web development?

Advantages of using Rails for web development include:

  • Convention over Configuration (CoC) reduces boilerplate code and improves development speed.
  • Built-in ORM (ActiveRecord) simplifies database interactions.
  • Abundant gems and plugins enhance productivity and extend functionality.
  • MVC architecture promotes modular development and code organization.
  • RESTful design encourages the creation of clean and predictable APIs.
  • Integrated testing tools (RSpec, Capybara) facilitate test-driven development (TDD).
  • Active community and extensive documentation.

14. What is the role of the Rails router?

The Rails router is responsible for mapping incoming HTTP requests to the appropriate controller actions. It matches URLs to route patterns and directs the requests to the corresponding controllers.

Example:

Ruby
# Configuring a custom route to handle a specific URL pattern
get '/about', to: 'pages#about'

In this example, the router maps the ‘/about’ URL to the ‘about’ action in the ‘PagesController.’

15. What is CSRF, and how does Rails protect against it?

CSRF (Cross-Site Request Forgery) is an attack where a malicious website tricks a user’s browser into making an unintended request to another site where the user is authenticated.

Rails protects against CSRF attacks by using an authenticity token (also known as CSRF token) that is included in every form generated by Rails. When a user submits a form, Rails checks that the token matches the one stored in the session, ensuring that the request originated from the same application and not from an attacker’s site.

Ruby
# Example of using CSRF protection in a form
<%= form_with(model: @post) do |form| %>
  <%= form.text_field :title %>
  <%= form.text_area :content %>
  <%= form.submit %>
<% end %>

16. What is the difference between “render” and “redirect_to” in Rails?

render and redirect_to are used to control the flow of a Rails application.

  • render: Used to render a specific view template within the current request/response cycle. It does not trigger a new HTTP request.
  • redirect_to: Used to send an HTTP redirect response to the client, instructing the browser to make a new request to a different URL.

Example:

Ruby
# Render a view template
def show
  @post = Post.find(params[:id])
  render :show
end

# Redirect to a different URL
def create
  @post = Post.new(post_params)
  if @post.save
    redirect_to @post
  else
    render :new
  end
end

17. What is the “flash” in Rails?

The “flash” in Rails is a special hash that is used to display temporary messages between actions. Flash messages are typically used to show success or error messages to users.

Example:

Ruby
# Setting a flash message
def create
  @post = Post.new(post_params)
  if @post.save
    flash[:success] = 'Post successfully created!'
    redirect_to @post
  else
    flash[:error] = 'Failed to create the post.'
    render :new
  end
end

# Displaying flash messages in the view
<% flash.each do |type, message| %>
  <div class="alert alert-<%= type %>">
    <%= message %>
  </div>
<% end %>

18. What are helpers in Rails?

Helpers in Rails are modules that contain methods used to assist views and templates. They provide reusable functionality and help keep views clean and focused on presentation logic.

Example:

Ruby
# A custom helper method to format a date
module ApplicationHelper
  def formatted_date(date)
    date.strftime('%B %d, %Y')
  end
end

In the above example, the formatted_date method can be used in views to display dates in a specific format.

19. How can you implement caching in Rails?

Caching in Rails helps improve application performance by storing frequently accessed data in memory or on disk, reducing the need to generate the same content repeatedly.

Example:

Ruby
# Caching the result of an expensive database query for 1 hour
def index
  @users = Rails.cache.fetch('all_users', expires_in: 1.hour) do
    User.all.to_a
  end
end

In this example, the @users variable will be cached with the key ‘all_users’ for one hour. Subsequent requests will use the cached data instead of querying the database again.

20. What is a Gemfile and Gemfile.lock in Rails?

A Gemfile in Rails is a plain text file that lists all the Ruby gems (dependencies) required for the application to run. It defines the gems, their versions, and any additional configuration for each gem.

Example:

Ruby
# Gemfile
source 'https://rubygems.org'

gem 'rails', '6.1.4'
gem 'sqlite3', '~> 1.4.2'
gem 'devise', '~> 4.8'

The Gemfile.lock is a generated file that locks the versions of all gems and their dependencies. It ensures that the application uses the same versions of gems across different environments.

21. Explain the Rails testing philosophy.

Rails follows a testing philosophy based on Test-Driven Development (TDD) and Behavior-Driven Development (BDD). The primary testing frameworks used in Rails are RSpec (for unit testing) and Capybara (for integration testing).

The testing philosophy in Rails emphasizes writing tests before writing the actual application code. It ensures that the code is well-tested, which leads to better code quality, reduces bugs, and makes it easier to refactor the codebase.

22. What are filters in Rails?

Filters in Rails are methods that can be executed before, after, or around specific controller actions. They are used to perform common tasks like authentication, logging, and authorization.

Example:

Ruby
class UsersController < ApplicationController
  before_action :authenticate_user, only: [:edit, :update]

  def edit
    # Edit action logic
  end

  def update
    # Update action logic
  end

  private

  def authenticate_user
    redirect_to login_path unless current_user
  end
end

In this example, the authenticate_user method is executed before the edit and update actions to ensure that the user is authenticated before accessing those pages.

23. What is Rack middleware in Rails?

Rack middleware in Rails is a layer that sits between the web server and the Rails application. It allows developers to add additional functionality to the request-response cycle, such as request/response modification, authentication, and caching.

Each middleware is a Ruby class that responds to the call method. When a request is received by the server, it passes through the middleware stack, and each middleware can perform its specific tasks before passing the request to the Rails application.

24. What are Rails plugins, and when should we use them?

Rails plugins are modular pieces of functionality that can be added to a Rails application. They are distributed as Ruby gems and can extend the core functionality of the framework or add new features.

Rails plugins should be used when you want to reuse functionality across multiple applications or when you want to encapsulate complex logic that doesn’t belong in the main application codebase.

Example:

Ruby
# A sample Rails plugin for calculating factorial
# lib/factorial.rb
class Factorial
  def self.calculate(n)
    return 1 if n == 0
    n * calculate(n - 1)
  end
end

The above Rails plugin can be used in any Rails application that requires factorial calculations by simply including the gem and calling the Factorial.calculate method.

25. What is the asset pipeline in Rails?

The asset pipeline in Rails is a feature that manages and processes assets (e.g., JavaScript, CSS, and images) in a Rails application. It compiles and compresses assets to improve loading speed and organizes them for easy use.

Example:

Ruby
/* app/assets/stylesheets/application.css */
body {
  background-color: #f5f5f5;
}

In this example, the ‘application.css’ file is part of the asset pipeline, and it will be processed and included in the final application layout.

26. How does Rails manage database transactions?

Rails uses the concept of database transactions to ensure the consistency and integrity of the data. When multiple database operations need to be executed as a single unit, they are wrapped in a transaction. If any part of the transaction fails, the entire transaction is rolled back, and no changes are persisted to the database.

Example:

Ruby
def transfer_funds(sender, receiver, amount)
  ActiveRecord::Base.transaction do
    sender.balance -= amount
    sender.save!

    receiver.balance += amount
    receiver.save!
  end
rescue ActiveRecord::RecordInvalid => e
  # Handle the error or raise it again
end

In this example, the transfer_funds method performs a fund transfer between two accounts. The entire operation is wrapped in a transaction to ensure the data remains consistent even if there is an error during the transfer.

27. What is the purpose of Rake tasks?

Rake tasks in Rails are scripts that automate common tasks and can be run from the command line using the rake command. They are defined in ‘Rakefile’ or in separate files within the ‘lib/tasks’ directory.

Rake tasks can be used for tasks like database seeding, data imports, asset compilation, and more. They simplify repetitive actions and allow developers to run tasks with a single command.

28. What are some ways to improve the performance of a Rails application?

Some ways to improve the performance of a Rails application include:

  • Caching frequently accessed data.
  • Optimizing database queries and indexing.
  • Minimizing the use of external services in critical paths.
  • Utilizing background jobs for time-consuming tasks.
  • Enabling server and database query caching.
  • Using a Content Delivery Network (CDN) for static assets.
  • Profiling and optimizing code for bottlenecks.

29. What is the difference between “include” and “extend” in Ruby?

includeextend
Used to add instance methods from a module to a class.Used to add class methods from a module to a class or object.
The module’s methods become available to instances.The module’s methods become available as class/module methods.
Supports multiple inclusion (mixins).Supports multiple extension (mixins).
Syntax: include ModuleNameSyntax: extend ModuleName

30. What is meant by “Convention over Configuration” in Rails?

“Convention over Configuration” (CoC) is a principle in Rails that emphasizes using sensible default conventions to reduce the need for explicit configurations. It allows developers to focus on writing application code rather than boilerplate configurations.

By following conventions, Rails can automatically infer things like database table names, class names, route mappings, and more, based on consistent naming and file organization. Developers only need to specify configurations when they deviate from these conventions.

For example, when creating a new Rails model named User, Rails will automatically assume that the corresponding database table is named users, and the model class will be User. This is possible because of the CoC principle.

Intermediate Questions

1. How does Ruby on Rails use the MVC framework? Give details.

Ruby on Rails (RoR) follows the Model-View-Controller (MVC) architectural pattern, which separates the application into three main components:

  1. Model: The model represents the data and business logic of the application. It interacts with the database and defines the structure of the data and the operations that can be performed on that data.
  2. View: The view represents the presentation layer of the application. It is responsible for displaying the data to the users. Views are typically written in HTML with embedded Ruby code (ERB) to dynamically render data.
  3. Controller: The controller handles the user’s requests and acts as an intermediary between the model and the view. It processes incoming HTTP requests, retrieves data from the model, and passes it to the view for rendering.

Here’s a high-level overview of how Ruby on Rails uses the MVC framework when a user interacts with a web application:

  1. The user makes an HTTP request to the Rails application (e.g., accessing a URL).
  2. The request is routed to the appropriate controller action based on the URL and HTTP method.
  3. The controller action interacts with the model to retrieve the required data or update the database.
  4. The controller then passes the data to the view for rendering the response.
  5. The view combines the data with the HTML template and generates the final HTML output.
  6. The controller sends the HTML response back to the user’s browser.

2. What are the different server options available for running a Rails application?

Ruby on Rails applications can be run on various servers, including:

  • WEBrick (default development server)
  • Apache with Passenger
  • Nginx with Passenger
  • Puma
  • Unicorn
  • Thin
  • Phusion Passenger Standalone

3. How is an HTTP request processed by a Rails application?

When an HTTP request is made to a Rails application, it goes through the following steps:

  1. The request is received by the web server.
  2. The web server forwards the request to the Rails application.
  3. Rails routes the request to the appropriate controller and action.
  4. The controller processes the request and interacts with the model if necessary.
  5. The controller renders the view (response) and sends it back to the user.

Here’s a simplified code example to illustrate this process:

Let’s assume we have a simple Rails application with a controller called HomeController and an action index:

Ruby
# routes.rb
Rails.application.routes.draw do
  get 'home/index'
end

# controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    @greeting = 'Hello, World!'
  end
end

# views/home/index.html.erb
<!DOCTYPE html>
<html>
<head>
  <title>Home</title>
</head>
<body>
  <h1><%= @greeting %></h1>
</body>
</html>

When a user accesses the URL associated with the HomeController#index action (e.g., /home/index), the request is processed as follows:

  1. The request is received by the Rails application.
  2. The route get 'home/index' matches the URL, and the request is routed to the HomeController#index action.
  3. The index action in the HomeController is executed, setting the @greeting instance variable.
  4. Rails automatically renders the views/home/index.html.erb template, substituting @greeting in the HTML.
  5. The generated HTML response is sent back to the user’s browser.

4. Explain the purpose of each type of Rails test (Unit, Functional, Integration).

  • Unit Test: Tests individual components, such as models and methods, in isolation to ensure they behave correctly.
  • Functional Test: Tests the behavior of controller actions and their interactions with models and views.
  • Integration Test: Tests the entire application’s behavior as a whole, including interactions between controllers, models, and views.

5. What is a polymorphic association in Rails?

A polymorphic association allows a model to belong to multiple other models on a single association. It’s typically used when a model can be associated with various other models without knowing the specific association at the time of definition.

Example:

Ruby
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Article < ApplicationRecord
  has_many :comments, as: :commentable
end

class Photo < ApplicationRecord
  has_many :comments, as: :commentable
end

6. How does the database abstraction work in Rails?

Rails uses an Object-Relational Mapping (ORM) technique for database abstraction. The ORM allows developers to interact with the database using Ruby objects instead of writing raw SQL queries.

Example:

Ruby
# Model representing a database table
class User < ApplicationRecord
end

# Create a new user record and save it to the database
user = User.new(name: 'John Doe', email: 'john@example.com')
user.save

# Retrieve users from the database
users = User.where(role: 'admin')

# Update an existing record
user = User.find_by(id: 1)
user.update(name: 'Jane Doe')

7. What are ActiveJob and Sidekiq, and how would you use them in a Rails application?

  • ActiveJob: A framework for declaring background jobs in Rails applications in a consistent and abstracted manner.
  • Sidekiq: A popular background processing library for Rails that uses Redis for queuing and processing jobs.

Example:

Ruby
# Define a sample job using ActiveJob
class SampleJob < ApplicationJob
  queue_as :default

  def perform(*args)
    # Some time-consuming task here
  end
end

# Enqueue the job for background processing
SampleJob.perform_later(arg1, arg2)

# Sidekiq configuration (config/sidekiq.yml)
---
:verbose: true
:concurrency: 5
:queues:
  - default

8. What is the difference between “includes”, “joins”, and “references” in ActiveRecord?

  • includes: Eager loads associated records to avoid N+1 query problems.
  • joins: Performs a SQL inner join to retrieve records based on association conditions.
  • references: Specifies a table to be joined when using the joins method.

Example:

Ruby
# Using includes
users = User.includes(:posts).where(age: 18)
# This avoids N+1 query issue when accessing posts: users.each { |user| user.posts }

# Using joins and references
users = User.joins(:posts).where(posts: { published: true })
# The references method is needed when using joins with conditions on associated tables

9. What are Rack and Middleware in Rails?

  • Rack: A minimal interface between Ruby web servers and web frameworks. It provides a common API for web servers to interact with Ruby frameworks.
  • Middleware: Middleware in Rails is any component that sits between the web server and the application, processing requests and responses. It adds functionalities like logging, authentication, etc.

10. How does Rails handle sessions and cookies?

Rails uses cookies to store session data on the client-side. The session data is serialized, encrypted, and sent to the client in a cookie. On subsequent requests, Rails decrypts the cookie to retrieve the session data and make it available to the application.

Example:

Ruby
# Setting a session variable
session[:user_id] = 1

# Accessing a session variable
user_id = session[:user_id]

11. Explain how Rails implements AJAX.

Rails supports AJAX through the use of Unobtrusive JavaScript (UJS) and the remote: true option.

Example:

Ruby
# Controller action with AJAX response
def update
  @user = User.find(params[:id])
  if @user.update(user_params)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js   # renders update.js.erb
    end
  else
    # Handle error
  end
end
Ruby
// views/users/update.js.erb
$("#user-info").html("<%= j render @user %>");

This example will update the user information on the page using AJAX without a full page reload.

12. What is meta-programming in Ruby? Give examples of how it could be used in Rails.

Meta-programming in Ruby refers to the ability of a program to modify or extend itself during runtime. It allows developers to write code that can generate other code, modify classes, add methods dynamically, etc.

Example in Rails (defining dynamic methods):

Ruby
# Assuming we have a model called "Product" with an attribute called "status" (integer)

# Using meta-programming to define dynamic finder methods for different statuses
[0, 1, 2].each do |status|
  define_method("status_#{status}") do
    self.class.where(status: status)
  end
end

# Now, we can call these methods on Product instances like:
active_products = Product.status_1
inactive_products = Product.status_0

13. What is “strong parameters” in Rails, and why is it important?

Strong Parameters is a security feature in Rails that prevents mass assignment vulnerabilities by specifying which parameters are allowed to be used in controller actions. It helps protect against unauthorized or malicious updates to the model attributes.

Example:

Ruby
# In a controller
class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      # Successfully created the user
    else
      # Handle errors
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password)
  end
end

In this example, only the name, email, and password attributes are permitted to be mass-assigned when creating a new user. Other attributes won’t be accepted, adding an extra layer of security.

14. What is the role of I18n in Rails?

I18n (Internationalization) in Rails provides a way to support multiple languages and translations in an application. It allows developers to externalize and manage text translations for different locales, making it easier to adapt the application to different regions and languages without changing the code.

Example:

Ruby
# config/locales/en.yml
en:
  hello: "Hello, %{name}!"
Ruby
Deepak Vishwakarma

Founder

RELATED Articles

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.