![]() |
VOOZH | about |
Ruby on Rails, often shortened to Rails, is a server-side web application framework written in Ruby under the MIT License. Rails is known for its ease of use and ability to build complex web applications quickly. It was created by David Heinemeier Hansson and was first released in 2004. Now, Over 3.8 million websites currently use Ruby on Rails, with over 600,000 active sites. This translates to roughly 5.3% of all websites being built with Rails.
Here, we provided over 50+ Ruby on Rails Interview Questions and Answers tailored for both beginners as well as for experienced professionals with 2, 7, or up to 10 years of experience. Here, we cover everything about Ruby on Rails from basic concepts to advanced concepts such as Core Syntax, OOPs concepts, Model-View-Controller (MVC) architecture, Active Record, CoC Principle, Routing, Authentication and authorization, API development, Security, Deployment, Caching, etc., and more that help you to crack your next Rails interview.
Table of Content
Ruby on Rails is an open-source, server-side web application development framework that is written in the Ruby programming language.
In Rails, the ORM or Object Relationship Model indicates that your classes are mapped to the database table, and objects are directly mapped to the table rows. The attributes and relationships of objects in an application may be easily stored and retrieved from a database using ORM, which requires less overall database access code and does not require writing SQL queries directly.
| Property | False | Nil |
|---|---|---|
| Data Type | Boolean | NilClass (special value) |
| Valid Value | Yes (represents "not true") | Yes (represents absence of value) |
| Object Type | FalseClass | NilClass |
| Represents | "Not true" | Absence of a value (nothing, void) |
| Property | String | Symbol |
|---|---|---|
| Definition | Sequence of characters | Similar to string, prefixed by colon (':') |
| Mutability | Mutable (can be changed) | Immutable (cannot be changed) |
| Memory Allocation | Separate memory for each string | Single instance per symbol |
| Example | name = "Geeksforgeek" | status = :geeksforgeek |
A Rails migration is a tool for altering the database schema of an application. Instead of handling SQL scripts, you use a domain-specific language to define database modifications (DSL). Because the code is database-agnostic, you can quickly port your project to a different platform. Migrations can be rolled back and managed alongside your application source code
Here are the functions of rails migration:
Mixin in ruby allows modules to access instance methods of another one using the include method. Mixin provides a controlled way of adding functionality to classes. The code in the mixin starts to interact with the code in the class. In ruby, a code wrapped up in a module is called mixins that a class can include or extend. A class consists of many mixins.
There are three different types of association relationships in Ruby on Rails:
Scaffolding in Rails is a way to generate a basic structure for your application, including the necessary files and code to perform CRUD (Create, Read, Update, and Delete) operations.
for more: Ruby on Rails - Scaffolding
In Ruby on Rails, the three default environments are:
The three primary components of Ruby on Rails are:
1. Model:
2. View:
3. Controller:
In Ruby projects, a Gemfile is a file that contains the list of Gem dependencies of the project. The Gemfile should be present at the root of the project. You can specify your list of gems with their version number.
MVC, or Model-View-Controller, is a software design pattern commonly used in web development frameworks like Ruby on Rails. It divides the application into three interconnected components, each with its responsibilities:
fro more: Ruby on Rails - MVC
Garbage collection is a technique for controlling the amount of memory computer programs use. Garbage collection and other memory management techniques, like reference counting, work by having the language keep track of which objects are used by a program rather than the developer.
for more: Garbage Collection in Ruby on Rails
Ruby class libraries consist of a variety of domains, such as thread programming, data types, various domains, etc. These classes give flexible capabilities at a high level of abstraction, giving you the ability to create powerful Ruby scripts useful in a variety of problem domains. The following domains that have relevant class libraries are,
DRY, which stands for ‘don’t repeat yourself,’ is a principle of software development that aims at reducing the repetition of patterns and code duplication in favor of abstractions and avoiding redundancy.
Some Benefits of using Rails on Rails in 2024 is:
for more: Features of Ruby on Rails
Nested layouts are used when you want to create a hierarchy of layouts, where one layout file wraps another layout file. This can be useful when you have common elements shared across multiple pages, but some pages have additional layout requirements.
The delete method is used to remove records from the database. Unlike the destroy method, which triggers callbacks and validations, delete directly removes records without any additional processing, making it faster but bypassing these mechanisms.
For example, suppose we have a User model and want to delete a specific user with an ID of 1:
user = User.find(1)user.deleteThis code will delete the user with an ID of 1 from the database immediately. Alternatively, if we want to delete all users with a certain condition, such as users with the age of 30:
User.where(age: 30).delete_allThis command will remove all users whose age is 30 from the database in a single operation.
# symbol followed by your comment text is used for adding comments in Ruby on Rails. Comments are ignored by the Ruby interpreter but help document your code. (Single line comment).
Both can be used for strings, but double quotes allow string interpolation (embedding variables within the string using #{})
Rails filters are methods that run before or after a controller’s action method is executed. They are helpful when you ensure that a given block of code runs with whatever action method is called.
Rails support three types of filter methods:
fro more: Ruby on Rails Filters - GeeksforGeeks
A helper is a method that is (mostly) used in your rails views to share reusable code. Rails comes with a set of built-in helper methods. If you are writing custom helper methods, the correct directory path is app/helpers
Instructions:
Render:
Example:
In this example, when the ‘show’ action of the ‘ArticlesController’ is called, it fetches an article and renders the ‘show.html.erb’ template, passing it the ‘@article’ instance variable.
Redirect_to:
Example:
In this example, after creating a new article, if the article is successfully saved, the user is redirected to the show page of the newly created article using 'redirect_to' @article'. If there are validation errors, the 'new' template is rendered again using 'render 'new''.
In Ruby on Rails (ROR), the active job is the framework known for declaring, scheduling, and executing background jobs and making them run on various queuing backends.
Example:
Suppose we have to send a professional email that includes thousands of registered employees. Each email takes around 1 second. To send an email to 1500 users will take 1500 seconds - approximately 25 min.
We would have to wait 25 minutes for the completion of this job, and no user would prefer to wait that long.
If we implement this with an active job, background jobs will run parallel to the normal flow of requests. We can access other applications along with emailing all the employees with ease.
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. Let’s say you have 25 javascript files and 25 CSS files (hopefully you won’t but who knows). Every time your app interacts with each one of those files it will make a request. Websites browsers are limited to the number of requests they can make at once so hitting all 50 of these files and then some is going to slow down your app. The asset pipeline takes care of this for you.
The asset pipeline will concatenate all of these files into one type. This means there will be one Javascript file and one CSS file generated by Rails. This makes your site much more efficient.
The asset pipeline does three main things:
Callbacks are methods that get called at certain moments of an object’s life cycle. With callback, it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
for more: What are Callbacks in Ruby on Rails?
There are several types of callbacks in Ruby on Rails. Here is a list with all the available Active record callbacks, listed in the same order in which they will get called during the respective operations:
Creating anWhen object:
Updating an object:
Destroying an object:
Polymorphic association is a type of association that allows a model to belong to more than one other model, where the associated model can be of different types. This is particularly useful when you have a situation where a single model needs to be associated with multiple other models.
Both has_many :through and has_and_belongs_to_many are association types in Ruby on Rails for defining many-to-many relationships between models. While they achieve similar goals, they have differences in terms of flexibility, functionality, and usage.
has_and_belongs_to_many (HABTM):
has_many :through:
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database).
You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.
Active Storage is a built-in library in Ruby on Rails that provides a way to handle file uploads and storage in Rails applications. It simplifies the process of uploading files to cloud storage services like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage, as well as local disk storage.
To use Active Storage in a Rails application, you typically follow these steps:
if you want to know more about: How to Upload Files in Ruby on Rails?
In Ruby on Rails, the term “accessor” typically refers to methods that allow you to read and write instance variables of an object. Accessors provide a way to interact with the internal state of an object, and they are commonly used to encapsulate and control access to attributes.
There are three main types of accessors in rails:
attr_reader: This method creates a getter method for the specified instance variable. Getter methods allow you to retrieve the value of an instance variable but do not allow direct modification of the variable's value from outside the object.
Example:
attr_writer: This method creates a setter method for the specified instance variable. Setter methods allow you to modify the value of an instance variable but do not allow direct access to its value.
Example:
attr_accessor: This method creates both getter and setter methods for the specified instance variable. It provides both read and write access to the variable's value.
Example:
When you call super with no arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method with the same name as where you called super from, along with the arguments that were passed to that method.
When we use super(), it sends no arguments to the parent.
Example of super:
In this example, super(name) is used within the initialize method of the Child class to call the initialize method of the Parent class with the name argument.
Example of super():
In this example, super() is used within the greeting method of the Child class to call the greeting method of the Parent class without passing any arguments.
In Ruby on Rails, there are several types of associations that you can define between ActiveRecord models. These associations help establish relationships between different models in your application's database schema. The main types of associations in Rails are:
The skip_callback method in Rails allows you to temporarily disable a callback for a specific object. This can be useful in situations where you want to prevent a callback from running under certain conditions.
Here’s an explanation of how ‘skip_callback’ works:
Skip_callback(:save, :before, :method_name)
This line of code tells Rails to skip the method_name callback that would normally run before saving an object.
Here's a breakdown of the parameters:
Here’s an example to illustrate how you might use ‘skip_callback’:
In Ruby on Rails, a concern is a way to share code across different parts of your application in a modular and reusable manner. Concerns are typically used to extract common functionality from models, controllers, or other parts of the Rails application into separate modules, making the code more maintainable and easier to understand.
Here’s how you can use a concern in Rails:
1. Create a Concern Module: First, you create a module that contains the shared functionality. You typically place these modules in the ‘app/controllers/concerns’ or ‘app/models/concerns’ directory, depending on whether the concern is related to controllers or models.
For example, let's say you have a ‘User’ model and you want to add some authentication-related methods. You could create a concern like this:
2. Include the Concern: Once you've defined the concern, you include it in the appropriate class (e.g., a model or a controller). You do this using the include method inside the class definition.
For example, to include the Authentication concern in the User model:
By including the concern, all the methods defined in the concern module become available to instances of the User class.
3. Use the Concern Methods: Now, you can use the methods defined in the concern as if they were defined directly in the class itself. For instance, if you included an authenticate method in the Authentication concern, you could call it on a User instance like so:
user = User.find(1)user.authenticate
When you call destroy on an Active Record object, it triggers the deletion of the corresponding record from the database. This is a destructive action, meaning it permanently removes the record from the database table.
Here’s how it works:
1. Locate the Record: First, you typically find the record you want to delete using methods like find or find_by. For example:
user = User.find(params[:id])
2. Destroy the Record: Once you have the record object, you can call the destroy method on it:
user.destroy
3. Database Operation: Behind the scenes, Rails generates and executes an SQL DELETE query to remove the record from the corresponding database table. This operation removes the record and any associated data (depending on your database constraints and associations).
4. Callbacks and Associations: The destroy method also triggers any callbacks defined in your model, such as before_destroy or after_destroy. Additionally, it automatically handles associated records based on your model's associations. For example, if a User has many Posts, deleting the user will also delete all associated posts.
It's important to note that calling destroy is irreversible and permanently deletes the record from the database. If you want to delete a record without triggering callbacks or validations, you can use the delete method instead. However, deletion bypasses these safeguards, so it should be used with caution.
Ruby supports single inheritance, where a class can only inherit from one superclass.
Ruby does not support multiple inheritance in the same way that some other programming languages like C++ do, where a class can inherit from more than one superclass directly. However, Ruby provides a feature called "mixins" which allows classes to inherit behavior from multiple sources indirectly.
Here's a simple explanation with an example:
In this example, MyClass includes both modules A and B. When you include a module in a class using the include keyword, all the methods defined within that module become available to instances of the class as if they were defined directly within the class itself.
Hash is a data structure that stores data in key-value pairs. It is similar to a dictionary in other programming languages. Hashes are often used to represent structured data, such as attributes of an object or parameters for a method.
Here’s an example of a hash in Ruby:
person = { "name" => "John", "age" => 30, "city" => "New York" }
In this hash, "name", "age", and "city" are the keys, and "John", 30, and "New York" are the corresponding values. You can access values in a hash using their keys:
puts person["name"] # Output: Johnputs person["age"] # Output: 30puts person["city"] # Output: New York
Hashes in Ruby are commonly used in Rails applications to represent data structures such as parameters passed to controller actions, configuration settings, or data retrieved from a database. They provide a convenient way to organize and access data in a structured manner.
Array#each:
Example:
numbers = [1, 2, 3, 4, 5] numbers.each { |num| puts num * 2 } # Output: 2 4 6 8 10
Array#map:
Example:
numbers = [1, 2, 3, 4, 5]doubled_numbers = numbers.map { |num| num * 2 }puts doubled_numbers.inspect # Output: [2, 4, 6, 8, 10]
In Ruby on Rails, self.up and self.down methods are used in the context of database migrations. Database migrations are a way to alter the database schema over time. These methods are typically used within migration files to define the changes that need to be made to the database schema when migrating to a new version of the application
Example:
In this example, we have a migration file named create_products.rb. Inside this migration file, there are up and down methods.
The up method is responsible for defining the changes that need to be made to the database schema when the migration is applied (i.e., when migrating "up" to a newer version of the application). In this case, it creates a new table called products with columns for name, description, and timestamps for tracking creation and updates.
The down method is responsible for defining how to reverse the changes made by the up method. It specifies how to undo the migration. In this case, it simply drops the products table if the migration needs to be rolled back (i.e., when migrating "down" to a previous version of the application).
In Ruby on Rails, yield is a special keyword used in conjunction with blocks to execute a block of code that is passed to a method. It allows methods to accept a block of code as an argument and then execute that block within the method's context.
Example:
In this example
Output:
Hello,
I'm Ruby on Rails.
Nice to meet you!In Ruby, closure is a function or a block of code with variables that are bound to the environment that the closure is called. In other words, closure can be treated like a variable that can be assigned to another variable or can be passed to any function as an argument.
Example:
In this example:
Terms | Python | Ruby |
|---|---|---|
| Definition | Python is a high-level programming language | Ruby is a general-purpose programming language |
| Object-oriented | Not a fully object-oriented programming language | Fully object-oriented programming language |
| Developing Environment | Multiple IDEs are supported | EclipseIDE is supported. |
| Mixins | Mixins can't be used | Mixins are used |
| Web frameworks | Django | Ruby on Rails |
| Libraries | Has a larger range of libraries | It has a smaller library than Python. |
| elseif | Elif | elseif |
| Developers | Created in 1991 by Guido van Rossum. | Created in 1995 by Yukihiro "Matz" Matsumoto. |
| Unset a variable | It will be present in the symbol table as long as it is in scope. | Once a variable is set, you can't unset it back. |
| Anonymous functions | Supports only lambdas | Supports blocks, procs, and lambdas. |
| lambda functions | It supports only single-line lambda functions | Its lambda functions are larger. |
| Functions | It has functions. | It doesn't have functions |
| Community | Focused on academia and Linux. | Mainly focused on the web. |
| switch/case statement | It doesn't support switch/case statements. | It supports switch/case statements. |
| yield keyword | It returns execution to the scope outside the function's invocation. External code is responsible for resuming the function. | It will execute another function that has been passed as the final argument, and then immediately resume. |
| Built-in-classes | Built-in classes can't be modified | Built-in classes can be modified. |
| Inheritance | Supports multiple inheritance. | Supports single inheritance |
| Tuples | It supports tuples. | It doesn't support tuples |
| Usage | Google, Dropbox, Instagram, Mozilla, Yahoo, Venom, Youtube | Apple, GitHub, Twitter, Hulu, ZenDesk, Urban Dictionary |
for more: Python vs Ruby