Show Menu
Cheatography

Ruby on rails interview Questions Cheat Sheet by

This interview Q&A cheat sheet offers a quick, easy reference to key interview strategies and commonly asked questions. Use it to refresh your preparation and boost your confidence before any interview!

What is Ruby on rails?

It is a Open-s­ource web applic­ation framework written in ruby
* It is designed to make web applic­ations easier by assuming what developers need to get started.
* It follows the model-­vie­w-c­ont­roller (MVC) archit­ecture pattern.

MVC Archit­ecture

In Ruby, MVC (Model­-Vi­ew-­Con­tro­ller) is a pattern used to organize code, especially in web applic­ations. It separates the applic­ation into three parts:
Model: Handles data and business logic. For example, it commun­icates with the database.
View: Manages the display. It’s what users see on the screen, like HTML or templates.
Controller: Connects Model and View. It receives user input, tells the Model to update or retrieve data, and then decides what View to show.
Flow: User -> Controller -> Model -> Controller -> View -> User.
In Ruby on Rails, this pattern helps keep code clean and organized, making it easier to manage large applic­ations.

MVC mean

MVC stands for Model-­Vie­w-C­ont­roller. It’s a software archit­ectural pattern commonly used in the develo­pment of user interf­aces, partic­ularly for web applic­ations.

Migration

It is a feature in rails that allow developers to manage & modify database schema over time.
* They are Ruby files used to make changes to the database, like creating tables or adding­/re­moving columns.
* Migrations make it easier to track and version change, rollback changes if necessary

Why Migrations are important

Migrations are important because they help track changes, keep the database schema consis­tent, and allow rolling back changes if needed.

Rails controller & purpose

Rails Controller handles requests and sends responses. It processes user actions, interacts with models to fetch or save data, and renders views or returns data (e.g., JSON).
* Contro­­llers are mapped to URLs using routes. They act as the middle layer between the user and the app's data or views.
Ex: User visits /articles. router directs request to Articl­esC­ont­rol­ler­#index, controller feteches all articles with Articl­e.all, controller sends data to view /returns a response.

Active Record

Active Record is the ORM (Objec­t-R­ela­tional Mapping) in Rails. It connects Ruby classes to database tables, making it easy to work with the database without writing SQL. Developers can use Ruby methods to interact with the data.

How active record works in database?

Maps models to database tables (e.g., User → users).
Provides methods for CRUD operations create, find, update, destroy
Ex: create­(User.create(name: " "), find(User.find(1)), update­(user.update(name: " "), destro­y(user.destroy).
Uses migrations to manage the database schema.
Handles relati­onships with associ­ations (e.g., has_many, belong­s_to).
Allows queries using Ruby methods instead of SQL.
User.w­her­e("age > ?", 18).or­der­(:name)

ORM( Object­-Re­lat­ion­al-­Map­ping)

It allows developers to interact with database using ruby code instead of writing raw SQL queries.
* In Rails, the ORM is Active Record, which maps models to database tables and provides methods for performing CRUD operations (Create, Read, Update, Delete).

Gemfile

It is used to manage the depend­encies of a Rails applic­ation. It specifies which gems (libra­ries) the applic­ation depends on and their versions.

Some Gem files

Authen­tic­ation & Author­ization: : Devise
* It handles user authen­tic­ati­on(­login, signup, password recover)
Database & ORM: bcrypt
* Handles password encryption when using has_se­cur­e_p­assword
Frontend: Bootstrap
* Add bootstrap style for responsive web design.
Kamineri: Adds pagination to your applic­ation.

Callbacks

Callbacks are methods that get triggered at certain points in the lifecycle of an object (like before saving, after updating, etc.).
Common callbacks include:
before­_save: Runs before a record is saved (on both create and update). Often used for tasks like formatting data.
after_save: Runs after a record is saved. Useful for tasks like logging or sending notifi­cat­ions.
before­_va­lid­ation: Runs before valida­tion. Can be used to modify attributes before validation checks.
after_­create: Runs after a new record is created., not on updates. Often used to trigger actions like sending welcome emails.
They are used to execute code at specific points to maintain data consis­tency or add additional logic.
 

Routing

Routing connects incoming requests (URLs) to the specific controller actions. Rails uses a routes.rb file to define routes.
A route can be defined as: get 'artic­les', to: 'artic­les­#index'
- a GET request to /articles will be handled by the index action in the Articl­esC­ont­roller.
- Rails has RESTful routes, which map standard URL patterns to controller actions (e.g., index, show, create, etc.) based on resources:
resources :articles
- This generates routes for all CRUD actions (index, show, new, edit, create, update, destroy).
Routes ensure incoming requests are directed to the right contro­llers and actions, organizing the applic­ation's structure effect­ively.

RESTful Archit­ecture

RESTful archit­ecture organizes web applic­ations around resources and standa­rdizes how they are accessed using HTTP verbs.
Resources: Treats entities (e.g., articles, users) as resources.
HTTP Verbs: Maps actions to HTTP methods:
GET: Retrieve data. POST: Create data.
PUT/PATCH: Update data. DELETE: Remove data.
RESTful Routes in Rails: Using resources, Rails generates routes for CRUD operat­ions.
resources :articles
GET /articles → Articl­esC­ont­rol­ler­#index (List all articles)
POST /articles → Articl­esC­ont­rol­ler­#create (Create a new article).
GET /artic­les/:id → Articl­esC­ont­rol­ler­#show (Show a specific article).
PATCH/PUT /artic­les/:id → Articl­esC­ont­rol­ler­#update (Update an article).
DELETE /artic­les/:id → Articl­esC­ont­rol­ler­#de­stroy (Delete an article).

Associ­ations & types

Associ­ations define relati­onships between models. They allow models to connect and share data easily.
Types
has_many: Defines one-to­-many relati­onship. A model "has many" other models.
Ex: User can have many Posts
belongs_to: Defines the opposite of has_many. A model "­belongs to" another model.
Ex: Post belongs to User
has_one: Defines a one-to-one relati­onship. A model "has one" other model. {{nl}Ex: User has one Profile
has_an­d_b­elo­ngs­_to­_many:Defines a many-t­o-many relati­onship without a join model.
Ex: Student can have many Courses, and a Course can have many Students.
has_many :through: Defines a many-t­o-many relati­onship with a join model.
Ex: Doctor has many Patients through Appoin­tments.

Polymo­rphic associ­ation

1 table associated with many tables
Ex: Post have likes, we use likes in post and comment

Active Record Vs Active Model

Active Record is an ORM framework in Rails that connects classes to database tables, enabling database operations through Ruby objects
Active Model provides modules for building custom models without a database, offering features like valida­tions, serial­iza­tion, and callbacks.

How do you handle errors?

Error handling in Rails is important for providing a smooth user experience and ensuring that users are properly informed when something goes wrong.

Partials

Partials in Rails are reusable pieces of view code that can be shared across multiple templates. They help reduce code duplic­ation and improve mainta­ina­bility by breaking views into smaller, modular compon­ents.
* Partial files start with an underscore (_) in their filename, e.g., _heade­r.h­tml.erb. They are called without the unders­core, e.g., <%= render 'header' %>.

Sessions

Sessions store user-s­pecific data across requests, typically used for authen­tic­ation and tracking user activity.
In Rails, session data is stored in a cookie (by default) and is accessible using the session hash.

Use of Rails console

The Rails console is an intera­ctive comman­d-line tool that allows developers to interact with their Rails applic­ation directly
Intera­cting with the Database: Test queries and CRUD operations without writing a full script.
Testing Code: Run snippets of Ruby or Rails code to verify functi­ona­lity.
Debugging: Inspect data, test methods, or debug applic­ation logic.

dependent destroy

Used in associ­ations specifies when record is deleted, all records are also deleted.
* Used in one-many or many-many
Ex: Post have comments, if post deleted comment also deleted
 

render vs redire­ct_to

render: It view template without making a new reques­t(r­edi­recting to browser). Simply display view..
redire­ct_to: Redirect browser to another action/ URL, triggering new request.

find vs find_by vs where

Find: It looks up a record using its primary key(id). It gives error if records isn't found.
find_by: Searches for first record that matches certain condition, return nil if no match found.
where: Finds all records that meet specific condition & returns them as list of objects.

resource vs resources

resource: It will give routes to all command operations except Index.
resources: It will give routes to all command operations

validate vs validates

validate : It is used to define custom valida­tions method.
validates : It is used to apply built-in validation rules to model attrib­utes.

delete vs destroy

delete: Doesnot execute callbacks.
destroy: executes callbacks

Purpose of rails db:seed task

The rails db:seed task is used to populate the database with initial data.

MVC In general

MVC is a design pattern used across different progra­mming languages, not just in Ruby. It divides code into Model, View, and Controller layers, which helps organize code by separating data handling, display, and logic, making it easier to develop and maintain applic­ations.

Active Record in rails

Active Record is part of the M in MVC pattern — which is the layer of the system respon­sible for repres­enting data and business logic.
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          More Cheat Sheets by akki_1

          Ruby Interview Questions Cheat Sheet