Ruby on Rails Interview Questions

Prepare better with the best interview questions and answers, and walk away with top interview tips. These interview questions and answers will boost your core interview skills and help you perform better. Be smarter with every interview.

  • 4.7 Rating
  • 53 Question(s)
  • 45 Mins of Read
  • 5214 Reader(s)


Ruby on Rails is an open-source, full-stack framework for developing database-backed web applications according to the Model-View-Control pattern. It allows you to write less code while accomplishing more than many other languages and frameworks.

Rails combine the Ruby programming language with HTML, CSS, and JavaScript to create a web application that runs on a web server.

Ruby on Rails uses the Model-View-Controller (MVC) architectural pattern in order to improve the maintainability of the application. 

The Model layer carries the business logic of the application and the rules to manipulate the data. In Ruby on Rails, the models are used to manage the interaction with their corresponding elements in the database.

The view is the front-end of the application, representing the user interface. Views are used to provide the data to the browsers that requested the web pages. Views can server content in several formats, such as HTML, PDF, XML, RSS and more.

Controllers interact with models and views. The incoming requests from the browsers are processed by the controllers, which process the data from the models and pass it to the views for presentation.

The Rails philosophy includes two major guiding principles:

DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing.

Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to do it, rather than requiring you to specify every little thing through endless configuration files.

David Heinemeier Hansson extracted Ruby on Rails from his work on the project management tool Basecamp at the web application company also called Basecamp.

 Hansson first released Rails as open source in July 2004.

Rails Latest version is 5.2.2 – Released on November 2018

To create a new rails application you need to use the following command

>rails new (app_name)

This will create a Rails application with the name mentioned.

For example

>rails new learning_app

This will create a Rails application called learning_app

By default Rails is shipped with three environments:

  • development
  • test
  • production
  1. The development environment is used on your development/local computer as you interact manually with the application.
  2. The test environment is used when running automated tests.
  3. The production environment is used when you deploy your application for the world to use.

You can connect to the database 

  • by setting an environment variable ENV['DATABASE_URL'] 
  • by using a configuration file called config/database.yml.

Using the config/database.yml file you can specify all the information needed to access your database:

  adapter: sqlite3
  database: blog_development
  pool: 5

This will connect to the database named blog_development using the sqlite3 adapter. 

This same information can be stored in a URL and provided via an environment variable like this:


Rails generators provide a method to generate the controllers.

Use the following command to create a controller

>rails generate controller  controller_name(comment)

This command will create following files in the application

Rails generators provide a method to generate the models.

Use the following command to create a model

>rails generate model  model_name(book)

This tells Rails to create 

  • a book.rb file inside app/models directory
  • a migration file inside the db/migrate directory that will form the books table 
  • associated test files.

Migration filenames include a timestamp to ensure that they are processed in the order that they were created.

>rails generate model book

This tells Rails to create a Book class for the Model, create a Migration that will form the books table and associated test files.

The above command created a migration file inside the db/migrate directory.

Migration filenames include a timestamp to ensure that they're processed in the order that they were created.

Add the table columns in db/migrate/20180709175423_create_books.rb file

def change 
create_table :users do |t|
t.string :name
t.string :author

Migration file uses a rake command to run the migration:

 > rake db:migrate

Create a new file and store with any name.The name should be followed by ".html.erb"

For example index.html.erb inside app/views directory.

“erb” stands for Embedded Ruby. When you define any file as ".html.erb" that means it is an HTML file with ruby code embedded in it.

Following is the syntax of using Ruby with HTML -

<% %>   # executes the Ruby script
<%= %>  # executes the Ruby script and displays the result

Rails application can be booted using the following command

>rails server

This command will fire up WEBrick, a web server distributed with Ruby.

A web server will use

  • Default environment as development
  • Default port as 3000
  • Address -

Navigate to http://localhost:3000  in your browser and you will see the Rails landing page.

Scaffolding is a quick way to produce some major pieces of an application. For auto-generating a set of models, views, and controllers for a new resource in a single operation, scaffolding is used.

Scaffolding is a technique supported by MVC frameworks in which programmers can specify how application database may be used.

Scaffolding was made popular by the Rails framework. It can be created using

>rails generate scaffold student name:string age:integer 

After scaffold run this command to migrate the table

>rake db:migrate

CRUD is an acronym for Create-Read- Update-Delete. 

  • Create new records in the database
  • Read or show the records in the database
  • Update existing records
  • Destroy or delete records

Scaffolding provides an interface to data in the database. The rails framework has the provision to generate scaffolding, Ruby classes and.erb files, for a CRUD application. Scaffolding consists of controller and model Ruby classes and view templates for creating retrieving, updating and deleting table rows.

Some of the Popular IDEs support Rails coding.

  • RubyMine
  • Komodo
  • TextMate
  • NetBeans
  • Eclipse
  • Heroku
  • Aptana Studio
  • Ice Coder 


A Rails View is an ERB program that shares data with controllers through mutually accessible variables. Action View is then responsible for compiling the response. Action View templates are written using embedded Ruby in tags mingled with HTML.

The final HTML output is a composition of three Rails elements: 

  • Templates 

  • Partials 

  • Layouts

Forms in web pages are an important interface to get the input from the user. Form markup becomes complex to write and maintain because of form control naming and their various attributes. 

Rails deals with these complexities by providing view helpers for generating form markup called Form Helpers. Form helpers can be written in your view files and you can embed html tags with form helpers.

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. This is a technique that lets you manage your database in the business logic language that you're most comfortable with. 

The active record pattern is an architectural pattern that stores in-memory object data in relational databases. In Rails, the advantages of ORM are implemented through Active Record.

Object Relational Mapping, which referred as ORM, in computer software is a programming technique.

An ORM framework is written in an object oriented language and encapsulated around a relational database.

  • Class mapped to table in the database 
  • Attributes of an object mapped to columns
  • Objects of the class mapped to rows in the table

A perfect ORM hides the details of a database's relational data behind the object hierarchy.

Active Record addresses

  • Representation of models and data
  • Data validations before storing into the database
  • Rather than SQL queries facilitates simple ruby wrapper methods
  • Associations between tables through models

The database structuring and schema management in Active Record is handled using migration libraries. Migrations are libraries of Active Record that allows you to modify database schema over time.

The following command used to create the migration file

>rails generate migration add_column_to_student

 It will create migration file under the path


Create Table

     create_table :table_name, :options

Add Columns

     add_column :books, :author, :string

Rename Columns

     rename_column :books, :author, :writer

Remove Columns

     remove_column :books, :body, :string

Drop table 

     drop_table :books

Migrations are stored as files in the db/migrate directory, one for each migration class. 

For example the name of the file is of the form YYYYMMDDHHMMSS_create_products.rb, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class should match the latter part of the file name. 

For example 20180906120000_create_products.rb should define class CreateProducts and 20180906120001_add_details_to_products.rb should define AddDetailsToProducts.

Rails use the timestamp form the migration file name to determine which migration should be run and in which order.

These timestamps of the migration files are stored in database automatically in the table name “schema_versions” every time when you run rake db:migrate command to track schema migrations.

Using Validations we can make sure that only valid data is stored in database. We have many ways to validate the input data before it is getting stored into database, including front end, backend and controller-level validations. In Rails a set of wrapper methods/helpers are available to validate data before saving into the database.

Validations should be written in model file. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well. Using built-in validation DSL, you can do several kinds of validations.

It validates whether a user has entered matching information like password or email in second entry field.
Validates value of an attribute using a regular expression to insure it is of correct format.
Validates whether value of an attribute is available in a particular given set.
Validates that length of an attribute matches length restrictions specified.
Validates whether an attribute is numeric.

When an Active Record model class fails a validation, it is considered an error. Each Active Record model class maintains a collection of errors, which display appropriate error information to the users when validation error occurs.

Association is a bond/connection between two Active Record models. Operations on objects become quite simple using Associations. The association describes the role of relations that models are having with each other.

Associations are defined in model files. Associations make common operations simpler and powerful.

Rails supports six types of associations:

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

This one-to-one association indicates that each instance of a model contains or possesses one instance of another model. For example, supplier  has only one account 

This is a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. 

For example, customers and orders

This one-to-many association indicates that each instance of the model has zero or more instances of another model. 

For example - customers and orders

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. In other words with polymorphic associations, a model can belong to more than one other model, on a single association.

For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:

If you have an instance of the Picture model, you can get to its parent via @picture.imageable. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface.

Callbacks are methods that will get called during object's lifecycle. Callbacks allow you to trigger logic before or after or around the alteration of an object's status. You can write a callback to get called during object’s CRUD and validations. Callbacks should be written in model files. It should be defined as a method, to get called during runtime.

  • before_save 
  • around_save
  • after_save
  • before_update
  • after_destory

We are using raw SQL to fetch database records. In Rails, there are better ways to carry out the same operations. The queries to the database are being managed by using the Query interface methods. Each method allows you to perform certain queries on your database without writing plain SQL. Rails provide methods for selecting records, limit, where, like, joins, order, group, and all other SQL queries.

Active Record gives lots of finder methods to do query interface. Few of them

  • distinct
  • group
  • limit
  • where
  • offset
  • order
  • references
  • select
  • uniq 
  • includes etc,.

The rails console command lets you interact with your Rails application from the command line. Rails console uses IRB, This is useful for testing out quick ideas with code and changing server-side data.

You can run this command

> rails console

If you want to test your code without changing any data, you can do

> rails console –sandbox

Layouts can be used to render a common view template around the results of Rails controller actions. Layout integration will give Look and feel for your application.

Layouts can be integrated in a Rails application in many ways.

  • From HTML templates/ UI design templates
  • Twitter Bootstrap Gem etc

MVC. After an HTTP request comes into your application and the router decides which controller and action to map it to, Rails packages up all the parameters that were associated with that request and runs the specified method in the specified controller.

Once that method is done, Rails will take any instance variables you’ve given it in that controller method and ship them over to the appropriate view file so they can be inserted into your HTML template and ultimately sent back to the browser.

It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.

A controller has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.

There are two kinds of parameters possible in a web application.


In this type, parameters are coming from the URL, called query string parameters. Parameters followed by (“?”).

2) Also, parameters are submitted to a controller when you submit the HTML form called POST Data.

To process or transfer data either

  •     from database queries to a user interface or
  •     even from user inputs to the database 

we need to have variables that are accessed throughout the object life cycle.

A controller uses two built-in methods to handle parameters: require and permit. 

For Example

    def student_params
      params.require(:student).permit(:name, :age)

The keys :name,:age will get stored in database if it defined in params and it should be permitted. Otherwise the value will be nil.

The Rails router recognizes URLs and dispatches them to a controller's action. It also generates paths and URLs. Rails router deals URLs in a different way from other language routers. It determines controller, parameters and action for the request.

 The Router provides a matching service by understanding the request/URL and matches it with the appropriate controller action to run.All routes are controlled by routes.rb under config folder.

Resource-based routes are the default routing in Rails. Resource-based routing is used to define all of the possible paths for a resource (controller). 

In routes, you need to define separate routes for CRUD actions. Instead of that, you can use the resourceful route which defines all the URLs in one line.

In routes.rb specify the resources with the controller name

resources :books

 The resource routing allows you to declare all of the common routes for a controller. It defines separate routes for index, create, update, read, delete and new actions in a single line of code.

Creating a resourceful route will also expose a number of helpers to the controllers in your application. 

In the case of

 resources :students

 The following URL/path helpers will be created

  • students_path returns /students
  • new_student_path returns /students/new
  • edit_student_path(:id) returns /students/:id/edit (for instance, edit_student_path(10) returns /students/10/edit)
  • student_path(:id) returns /students/:id (for instance, student_path(10) returns /students/10)

Rails session is only available in controller or view and can use different storage mechanisms. It is a place to store data from first request that can be read from later requests.To save and keep data across multiple requests, Rails uses the session.

A session is just a place to store data during one request that you can use during other requests. You can create sessions for each user in your application. User session can store small amounts of data (like id,name) that will be accessed between different requests. 

A session can be used in controller and the views.

The session can be accessed through the session instance method. If sessions will not be accessed in action's code, they will not be loaded.

Session values are stored using key/value pair like a hash. They are usually 32 bit character long string.In Rails, data can be save and retrieve using session method.

Creating a Session


Removing a session


Rails filters are methods that run before or after a controller's action method is executed. They are helpful when you want to ensure that a given block of code runs with whatever action method is called. Filters can be inherited, so you can set a common filter on ApplicationController, it will be run on every controller in Rails application.

Filters should be written in controller. Mostly Filters methods are private

Private methods are only accessible within the class in which they are defined.

ails support three types of filter methods:

  • Before filters
  • After filters
  • Around filters

Before filters are run on requests before the request gets to the controller’s action.

After filters are run after the action completes. It can modify the response.

Around filters may have logic before and after the action being run.

Action Mailer allows you to send emails from your application using mailer classes and views. This component inherits from ActionMailer::Base and lives in app/mailers.

This component has associated views that appear in app/views.

There are four steps in sending emails

  • First create the mailer 

>rails g mailer mailer_name(emailer)

  • Then define the mailer function 
  • Add the content to this email and store in corresponding view folder.
  • Then finally add the deliver method to call the mailer function in controller

If you have one Gmail account, using the SMTP setting of Gmail you can get real-time emails from your application.

As Action  Mailer now uses the Mail gem, this becomes a very simple configuration.

Add the following code in config/environments/development.rb

config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
  address:              '',
  port:                 587,
  domain:               '',
  user_name:            '',
  password:             '**********',
  authentication:       'plain',
  enable_starttls_auto: true  }

The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB.

Making the asset pipeline a core feature of Rails means that all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. The asset pipeline is enabled by default in Rails configuration.

The Ruby I18n (shorthand for internationalization) gem which is shipped with Ruby on Rails provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or for providing multi-language support in your application.

Rails I18n API focuses on:

  • providing support for English and similar languages out of the box
  • making it easy to customize and extend everything for other languages

Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.

Active Support does not load anything by default. It is broken in small pieces so that you can load just what you need.

To include active support add this line in your ruby file

require 'active_support'


Prepare better with the best interview questions and answers, and walk away with top interview tips. These interview questions and answers will boost your core interview skills and help you perform better. Be smarter with every interview.