Category: Ruby on Rails

  • Bundler

    In Rails, Bundler is a dependency management tool that ensures your application has the correct versions of the required gems. A gem in Ruby is a packaged Ruby library that provides functionality for Ruby applications. Gems are hosted on RubyGems.org, which is the official Ruby package repository.

    The main role of Bundler is to manage and install the gem dependencies specified in the Gemfile.

    When a new application is created, Rails does the following behind the scenes:

    • Generates the Gemfile with default gems.
    • Runs bundle install automatically, which:
    • Resolves dependencies.
    • Installs required gems.
    • Creates the Gemfile.lock file to lock exact gem versions.

    Gemfile

    When you create a new Rails application and run rails server, Rails internally calls Bundler to load the required gems. The rails new command sets up the Rails project and generates various files, including Gemfile.

    Here’s a section of the Gemfile created automatically by Rails new command:

    source "https://rubygems.org"# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
    gem "rails","~> 8.0.1"# The modern asset pipeline for Rails [https://github.com/rails/propshaft]
    gem "propshaft"# Use sqlite3 as the database for Active Record
    gem "sqlite3",">= 2.1"# Use the Puma web server [https://github.com/puma/puma]
    gem "puma",">= 5.0"# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
    gem "importmap-rails"# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
    gem "turbo-rails"# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
    gem "stimulus-rails"# Build JSON APIs with ease [https://github.com/rails/jbuilder]
    gem "jbuilder"

    It also runs bundle install, which resolves dependencies and creates Gemfile.lock.

    Gemfile.lock

    This file is auto-generated by Bundler when bundle install is run. It locks the exact versions of the installed gems to ensure consistency. For example −

    GEM
      remote: https://rubygems.org/
      specs:
    
    actioncable (8.0.1)
      actionpack (=8.0.1)
      activesupport (=8.0.1)
      nio4r (~>2.0)
      websocket-driver (>=0.6.1)
      zeitwerk (~>2.6)
    actionmailbox (8.0.1)
      actionpack (=8.0.1)
      activejob (=8.0.1)
      activerecord (=8.0.1)
      activestorage (=8.0.1)
      activesupport (=8.0.1)
      mail (&gt;=2.8.0)</pre>

    However, you need to run bundle install manually if you manually modify Gemfile (e.g., adding a new gem).

    If you pull the project from GitHub, you have to run bundle install since Gemfile.lock might not match your system. Sometimes, a required gem is missing when running rails server. You need to add a new gem to a Rails application when you require additional functionality that is not provided by the Rails framework itself.

    To add a New Gem, you can add it directly using Bundler −

    bundle add gem_name
    

    Or manually, add it to Gemfile −

    gem 'gem_name'

    Then run:

    bundle install
    

    Common Bundler commands are as follows:

    • bundle install − Installs all gems listed in Gemfile.
    • bundle update − Updates gems to the latest versions allowed by the Gemfile.
    • bundle exec <command> − Runs a command using gems from Bundler (e.g., bundle exec rails server).
    • bundle add <gem_name> − Adds a gem to the Gemfile and installs it.
    • bundle remove <gem_name> − Removes a gem from the Gemfile.
  • Rails Console

    Rails API provides a useful feature called Console. The console is an interactive tool for testing the code in our Rails application.

    Before opening a console session, let us define a Person model with name and age columns.

    rails generate model Person name:string age: integer
    
      invoke  active_record
      create  db/migrate/20250227112053_create_people.rb
      create  app/models/person.rb
      invoke  test_unit
      create  test/models/person_test.rb
      create  test/fixtures/people.yml

    This will create Person class derived from ApplicationRecord:

    classPerson<ApplicationRecordend

    As in the previous chapter, run the migration on this model.

    PSC:\Users\mlath\RubymineProjects\library> rails db:migrate==20250227112053CreatePeople: migrating =====================================-- create_table(:people)->0.0230s
    ==20250227112053CreatePeople: migrated (0.0247s)==============================20250227112941Persons: migrating ============================================20250227112941Persons: migrated (0.0000s)=================================

    Open a PowerShell or Command prompt if using Windows, or a terminal if on Ubuntu. Make sure that you are logged into the project directory (library in this case).

    PSC:\Users\mlath\RubymineProjects\library> rails console
    Loading development environment (Rails8.0.1)
    library(dev)>

    You can check the version of Rails installation in the console window.

    library(dev)>Rails.version
    =>"8.0.1"

    All the resources of the project, including the Person model can be accessed in the console. To get the list of columns defined in Person model, use column_names property.

    library(dev)>Person.column_names
    =>["id","name","age","created_at","updated_at"]

    Note that Rails adds created_at and updated_at columns.

    The new() function of the Person class creates a new Person object.

    library(dev)> p1 =Person.new(name:"Ravi", age:21)=>#<Person:0x000002ac6815e228 id: nil, name: "Ravi", 
       age:21, created_at:nil, updated_at:nil>

    The object is placed in the memory. To save it persistently in the database, call the save() function.

    library(dev)> p1.save
      TRANSACTION(0.6ms)BEGIN/*application='Library'*/TRANSACTION(0.7ms)BEGIN/*application='Library'*/PersonCreate(4.6ms)INSERTINTO"people"("name","age","created_at","updated_at")VALUES('Ravi',21,'2025-02-27 12:29:12.006534','2025-02-27 12:29:12.006534')RETURNING"id"/*application='Library'*/TRANSACTION(1.5ms)COMMIT/*application='Library'*/=>true

    The auto-created fields created_at and updated_at bear the time stamp:

    library(dev)> p1
    =>#<Person:0x000002ac6815e228
     id:1,
     name:"Ravi",
     age:21,
     created_at:"2025-02-27 12:29:12.006534000 +0000",
     updated_at:"2025-02-27 12:29:12.006534000 +0000">

    The create() function creates a new object and save it in the database.

    library(dev)>Person.create(name:"Raja", age:25)TRANSACTION(1.0ms)BEGIN/*application='Library'*/PersonCreate(2.8ms)INSERTINTO"people"("name","age","created_at","updated_at")VALUES('Raja',25,'2025-02-27 12:30:33.474115','2025-02-27 12:30:33.474115')RETURNING"id"/*application='Library'*/TRANSACTION(39.1ms)COMMIT/*application='Library'*/=>#<Person:0x000002ac690d6908
     id:2,
     name:"Raja",
     age:25,
     created_at:"2025-02-27 12:30:33.474115000 +0000",
     updated_at:"2025-02-27 12:30:33.474115000 +0000">

    The all() function retrieves all the records in the underlying table.

    library(dev)>Person.all
      PersonLoad(1.0ms)SELECT"people".*FROM"people"/* loading for pp */LIMIT11/*application='Library'*/=>[#<Person:0x000002ac690dc588
      id:1,
      name:"Ravi",
      age:21,
      created_at:"2025-02-27 12:29:12.006534000 +0000",
      updated_at:"2025-02-27 12:29:12.006534000 +0000">,#<Person:0x000002ac690dc308
      id:2,
      name:"Raja",
      age:25,
      created_at:"2025-02-27 12:30:33.474115000 +0000",
      updated_at:"2025-02-27 12:30:33.474115000 +0000">]

    Rails also adds id as the primary ley for the model. You can fetch a given record by calling the find() function and giving id as an argument.

    To find the record with id=1 −

    library(dev)> p1=Person.find(1)PersonLoad(0.9ms)SELECT"people".*FROM"people"WHERE"people"."id"=1LIMIT1/*application='Library'*/=>#<Person:0x000002ac690db048...

    To modify a record, assign a new value to one or more attributes (columns) and call save() function. Let us change the name of person with id=1 to Ravindra.

    library(dev)> p1.name="Ravindra"=>"Ravindra"
    library(dev)> p1.save
      TRANSACTION(0.6ms)BEGIN/*application='Library'*/PersonUpdate(4.2ms)UPDATE"people"SET"name"='Ravindra',"updated_at"='2025-02-27 12:34:14.306655'WHERE"people"."id"=1/*application='Library'*/TRANSACTION(38.3ms)COMMIT/*application='Library'*/=>true

    Note that Rails translates this function call to the equivalent UPDATE query.

    You can apply filter to conditionally fetch records from the underlying table. You can use all the comparison operators in the where() function.

    library(dev)>Person.where("age > ?",25)PersonLoad(1.7ms)SELECT"people".*FROM"people"WHERE(age >25)/* loading for pp */LIMIT11/*application='Library'*/=>[#<Person:0x000002ac6993ac98
      id:2,
      name:"Raja",
      age:30,
      created_at:"2025-02-27 12:30:33.474115000 +0000",
      updated_at:"2025-02-27 12:36:04.560314000 +0000">]

    Here also Rails internally executes an equivalent SELECT query .

    The update() function works as an equivalent foe assigning new value to a column and calling save() function. Let us update the name of a record with id=2.

    library(dev)> p1.update(name:"Rajendra")TRANSACTION(0.6ms)BEGIN/*application='Library'*/PersonUpdate(2.9ms)UPDATE"people"SET"name"='Rajendra',"updated_at"='2025-02-27 12:38:06.880558'WHERE"people"."id"=2/*application='Library'*/TRANSACTION(38.8ms)COMMIT/*application='Library'*/=>true

    How can you delete a record from the table? Let us first add a new record , Rails assigns a unique id to it.

    library(dev)>Person.create(name:"Roger", age:20)TRANSACTION(0.9ms)BEGIN/*application='Library'*/PersonCreate(2.9ms)INSERTINTO"people"("name","age","created_at","updated_at")VALUES('Roger',20,'2025-02-27 12:40:00.051918','2025-02-27 12:40:00.051918')RETURNING"id"/*application='Library'*/TRANSACTION(39.3ms)COMMIT/*application='Library'*/=>#<Person:0x000002ac69935f18
     id:3,
     name:"Roger",
     age:20,
     created_at:"2025-02-27 12:40:00.051918000 +0000",
     updated_at:"2025-02-27 12:40:00.051918000 +0000">
    library(dev)> p1 =Person.find(3)PersonLoad(0.9ms)SELECT"people".*FROM"people"WHERE"people"."id"=3LIMIT1/*application='Library'*/=>#<Person:0x000002ac6993e9d8...

    To delete an instance of the Person model, call the destroy function.

    library(dev)> p1.destroy
      TRANSACTION(0.6ms)BEGIN/*application='Library'*/PersonDestroy(2.0ms)DELETEFROM"people"WHERE"people"."id"=3/*application='Library'*/TRANSACTION(39.6ms)COMMIT/*application='Library'*/=>#<Person:0x000002ac6993e9d8
     id:3,
     name:"Roger",
     age:20,
     created_at:"2025-02-27 12:40:00.051918000 +0000",
     updated_at:"2025-02-27 12:40:00.051918000 +0000">

    This executes the DELETE query as can be seen from the console log.

    Most of the actions required to create and manage a Rails application are performed using various commands. For example Rails new creates the directory structure for a new application, Rails generate allows you to generate components such as ActiveRecord and migrations.

    Here is the list of Rails commands:

    • bin/rails console
    • bin/rails server
    • bin/rails test
    • bin/rails generate
    • bin/rails db:migrate
    • bin/rails db:create
    • bin/rails routes
    • bin/rails dbconsole
    • rails new app_name

    The dbconsole is also another useful console command. It opens the console of the corresponding database which you have used as a backend for your application. In this case, the library application has been created with PostgreSQL as the backend. Hence, dbconsole opens the psql console.

    C:\Users\mlath\RubymineProjects\library>rails dbconsole
    Passwordfor user postgres: 
    psql (16.2)WARNING:Console code page (437) differs from Windows code page (1252)8-bit characters might not work correctly.See psql reference
    
         page "Notes for Windows users"for details.Type"help"for help.
    library_development=#

  • Directory Structure

    When you use the Rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don’t have to provide any input.

    Shown below is a top-level view of a directory tree created by the helper script at the time of application creation. Except for minor changes between releases, every Rails project will have the same structure, with the same naming conventions. This consistency gives you a tremendous advantage; you can quickly move between Rails projects without relearning the project’s organization.

    To understand this directory structure, let’s use the application created in the Installation chapter. It can be created using a simple helper command −

    rails new myapp
    

    Directory Structure

    Now, go into the myapp application root directory. You will find a directory structure in Windows as follows −

    Ruby on Rails Directory Structure

    Folders and Files

    Each subfolder and the file in the application directory is created for a specific purpose. Now let’s explain the purpose of each directory.

    FolderPurpose
    app/It organizes your application components. It’s got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).
    bin/Contains the rails script that starts your app and can contain other scripts you use to set up, update, deploy, or run your application.
    config/It organizes your application components. It’s got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).
    db/Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory.
    lib/You’ll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries).
    log/Error logs go here. Rails creates scripts that help you manage various error logs. You’ll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log).
    public/Like the public directory for a web server, this directory has web files that don’t change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public).
    script/This directory holds scripts to launch and manage the various tools that you’ll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server).
    storage/Contains SQLite databases and Active Storage files for Disk Service. This is covered in Active Storage Overview.
    test/The tests you write and those that Rails creates for you, all goes here. You’ll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional).
    tmp/Rails uses this directory to hold temporary files (like cache and pid files) for intermediate processing.
    vendor/Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here, this includes vendored gems.
    .git/Contains Git repository files.
    .github/Contains GitHub specific files.
    .kamal/Contains Kamal secrets and deployment hooks.

    Apart from these directories, there will be the following files available in the application directory −

    FilePurpose
    config.ruRack configuration for Rack-based servers used to start the application.
    DockerfileConfiguration file for Docker.
    Gemfile
    Gemfile.lockThese files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem.
    RakefileThis file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.
    README.mdThis is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.
    .dockerignoreThis file tells Docker which files it should not copy into the container.
    .gitattributesThis file defines metadata for specific paths in a Git repository. This metadata can be used by Git and other tools to enhance their behavior.
    .gitignoreThis file tells Git which files (or patterns) it should ignore.
    .rubocop.ymlThis file contains the configuration for RuboCop.
    .ruby-versionThis file contains the default Ruby version.

    The app subdirectory includes the following folders −

    FolderPurpose
    app/controllersThe controllers subdirectory is where Rails looks to find the controller classes. A controller handles a web request from the user.
    app/helpersThe helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.
    app/modelsThe models subdirectory holds the classes that model and wrap the data stored in our application’s database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!
    app/viewsThe views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user’s browser.
    app/views/layoutsHolds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout:default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout.
  • Framework

    A framework is a program, set of programs, and/or code library that writes most of your application for you. When you use a framework, your job is to write the parts of the application that make it do the specific things you want.

    When you set out to write a Rails application, leaving aside the configuration and other housekeeping chores, you have to perform three primary tasks −

    Describe and Model your Application’s Domain

    The domain is the universe of your application. The domain may be a music store, a university, a dating service, an address book, or a hardware inventory. So here you have to figure out what’s in it, what entities exist in this universe and how the items in it relate to each other. This is equivalent to modeling a database structure to keep the entities and their relationship.

    Specify What can Happen in this Domain

    The domain model is static; you have to make it dynamic. Addresses can be added to an address book. Musical scores can be purchased from music stores. Users can log in to a dating service. Students can register for classes at a university. You need to identify all the possible scenarios or actions that the elements of your domain can participate in.

    Choose and Design the Publicly Available Views of the Domain

    At this point, you can start thinking in Web-browser terms. Once you’ve decided that your domain has students, and that they can register for classes, you can envision a welcome page, a registration page, and a confirmation page, etc. Each of these pages, or views, shows the user how things stand at a certain point.

    Ruby on Rails MVC Framework

    The Rails framework follows a Model View Controller (MVC) pattern. The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems.

    Model (ActiveRecord)

    It maintains the relationship between the objects and the database and handles validation, association, transactions, and more.

    This subsystem is implemented in ActiveRecord library, which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

    View (ActionView)

    It is a presentation of data in a particular format, triggered by a controller’s decision to present the data. They are script-based template systems like JSP, ASP, PHP, and very easy to integrate with AJAX technology.

    This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.

    Controller (ActionController)

    The facility within the application that directs traffic, on the one hand, querying the models for specific data, and on the other hand, organizing that data (searching, sorting, messaging it) into a form that fits the needs of a given view.

    This subsystem is implemented in ActionController, which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).

    Pictorial Representation of MVC Framework

    Given below is a pictorial representation of Ruby on Rails Framework −

    Rails Framework

    Directory Representation of MVC Framework

    Assuming a standard, default installation over Ubuntu Linux as explained in the Installation chapter, you can find them like this −

    Log into the gems directory of the installation directory of Ruby −

    malhar@ubuntu:~$ cd ~/.rvm/gems/ruby-3.4.1/gems

    You will see subdirectories including (but not limited to) the following −

    malhar@ubuntu:~/.rvm/gems/ruby-3.4.1/gems$ ls -1
    actioncable-8.0.1
    actionmailbox-8.0.1
    actionmailer-8.0.1
    actionpack-8.0.1
    actiontext-8.0.1
    actionview-8.0.1
    activejob-8.0.1
    activemodel-8.0.1
    activerecord-8.0.1
    activestorage-8.0.1
    activesupport-8.0.1
    addressable-2.8.7......

    Over a Windows installation, you can find them like this −

    Go to the directory where the gems are located −

    C:\Ruby33-x64\lib\ruby\gems\3.3.0\gems
    

    You will see subdirectories including (but not limited to) the following −

    MVC

    ActionView and ActionController are bundled together under ActionPack.

    ActiveRecord provides a range of programming techniques and shortcuts for manipulating data from an SQL database. ActionController and ActionView provides facilities for manipulating and displaying that data. Rails ties it all together.

  • Hello World

    To get the “Hello world” message displayed in the browser with a Rails application, you need to create a route, a controller with an action and a view.

    • route maps a request to a controller action. In Rails, a route is the part of the URL that determines how an incoming HTTP request is directed to the appropriate controller and action for processing.
    • Controller is a Ruby class, which inherits from ApplicationController class, and its public methods are actions.
    • Views in Rails are templates, usually written in a mixture of HTML and Ruby. They are saved with the .erb extension (stands for embedded Ruby).

    Rails Generate Command

    Rails comes with a powerful command line tool called the generate command. It can be used for different purposes. Different types of generators will be displayed with the following command −

    >rails generate
    Usage:
      bin/rails generate GENERATOR[args][options]General options:-h,[--help]# Print generator's options and usage-p,[--pretend]# Run but do not make any changes-f,[--force]# Overwrite files that already exist-s,[--skip]# Skip files that already exist-q,[--quiet]# Suppress status outputPlease choose a generator below.Rails:
      application_record
      authentication
      benchmark
      channel
      controller
      generator
      helper
      integration_test
      jbuilder
      job
      mailbox
      mailer
      migration
      model
      resource
      scaffold
    ...

    Rails Generate Controller Command

    Rails generators are built on top of Thor, a simple and efficient tool for building selfdocumenting command line utilities. Let us generate a Controller for our application.

    The syntax of the rails generate controller command is as follows −

    rails generate controller ControllerName[action1 action2 ...][options]

    In this syntax −

    • ControllerName − The name of the controller you want to create.
    • [action1 action2 …] − A space-separated list of actions (methods) you want to define in the controller.

    For each action, Rails will generate corresponding view files in the appropriate directory.

    Open your terminal, navigate to your Rails project directory, and run the following command to create a controller named index and an action named index.

    rails generate controller index index
    

    This command generates −

    • The controller itself
    • A views folder for the controller
    • A view file for the specified actions
    • A test file for this controller
    • A helper file for extracting logic in our views

    The following activity will appear in the terminal window −

    create  app/controllers/index_controller.rb
    
      route   get "index/index"
      invoke  erb
      create  app/views/index
      create  app/views/index/index.html.erb
      invoke  test_unit
      create  test/controllers/index_controller_test.rb
      invoke  helper
      create  app/helpers/index_helper.rb
      invoke  test_unit

    In Ruby on Rails, an action in a controller is essentially a method defined within the controller class.

    Edit the index_controller.rb file to include the definition of index action as follows −

    classIndexController<ApplicationControllerdefindexendend

    We now need to provide a template to be rendered by the index action. Rails assumes that the template is named as index.html and attaches .erb as its extension. This file embeds Ruby code inside HTML script.

    Open a new file in the editor. Save the following HTML code and save it as index.html.erb

    <h1 style="text-align: center;">Hello World</h1>

    To tell Rails the root route should render the index action, open the config/routes.rb file and define a route for the root URL (/). Modify it to look like this −

    Rails.application.routes.draw do
      root "index#index"end

    Run the Rails Server

    Rerun the Rails server if not already running, and visit the http://localhost:3000 URL, instead of the Rails welcome page, you should get the Hello World message displayed in the browser.

    Run the Rails Server
  • IDEs

    An Integrated Development Environment (IDE) is an essential software tool that makes the process of development and packaging process a lot easier, convenient and efficient. An IDE provides a one-stop solution for editing the code, compiling and debugging it, and running the application. IDEs also have features such as syntax highlighting, document generation, and version control etc.

    Several IDEs are available for Rails. This chapter introduces some of the widely used IDEs for Ruby on Rails.

    RubyMine

    Developed by JetBrains, RubyMine is one of the most popular IDEs amongst the Rails developers. Code completion, powerful refactoring and debugging and integration with Git are some of its important features. RubyMine also supports various web technologies, such as HTML, CSS, and JavaScript, thus making it a great choice for web development.

    RubyMine is a proprietary software, however it comes with a 30-day trial version. It is available for use on Windows, macOS as well as Linux. It can be downloaded from https://www.jetbrains.com/ruby/download/.

    For Ubuntu Linux, you can install RubyMine with the following command −

    sudo snap install rubymine classic
    

    To install on Windows, download the latest installer (RubyMine-2024.3.2.1.exe) and run the installation wizard, keeping most of the default settings.

    After the installation is complete, launch RubyMine and start a new Rails project.

    RubyMine

    Under the Rails tab, select application, specify the Ruby interpreter, Rails version and the project folder path.

    RubyMine 1

    Click on the Create button. RubyMine creates the folder structure of a Rails project. Open the terminal (View > Tool Windows > Terminal) and start the Puma server with the command −

    ~\RubymineProjects\NewRailsProject> rails server
    

    You can now visit http://localhost:3000 to get the welcome page displayed.

    VS Code

    Visual Studio code is one of the most popular IDEs as it supports multiple languages through its extensions library. You can customize the VS Code installation by loading certain Ruby and Rails-specific extensions.

    After launching the VS Code application, search and install the following extensions −

    Ruby LSP

    The Ruby LSP is an implementation of the language server protocol for Ruby, used to improve rich features in editors.

    Ruby LSP

    Rails

    This extension provides Ruby on Rails support for Visual Studio Code.

    Ruby Visual Studio Code

    Ruby Solargraph

    Solargraph is a language server that provides intellisense, code completion, and inline documentation for Ruby.

    Ruby Solargraph

    ERB Formatter

    This extension provides formatting for .erb files (embedded Ruby templates).

    ERB files

    After installing these extensions, you need to modify the GemFile in your application to install the corresponding gems.

    group :developmentdo# Use console on exceptions pages [https://github.com/rails/web-console]
      gem "web-console"
      gem "ruby-lsp"# For Ruby LSP in VS Code
      gem "solargraph"# For code intelligence and autocompletionend

    Then run the command −

    bundle install
    

    Restart VS Code and create a new Rails project.

    Other Popular IDEs and Code Editors

    In addition to RubyMine and VS Code, the following IDEs/code editors are also used for Rails development:

    Atom by GitHub is an open-source text editor. Atom can be customized for Ruby on Rails development environment with the installation of the Atom Ruby IDE package and other relevant plugins.

    Sublime Text is a lightweight text editor. With the addition of packages like Sublime Text 3 Ruby on Rails, it can work as a proficient Ruby on Rails IDE.

  • Installation

    To develop a web application using Ruby on Rails Framework, you need to install the following software −

    • Ruby
    • The Rails Framework
    • A Web Server
    • A Database System

    Ruby is a programming language, whereas Rails is a web development framework built on Ruby. Rails includes a built-in web server called Puma for local development purposes. For Production: You’ll need a proper web server setup like Puma with Nginx, lightTPD or Apache.

    Rails works with many database systems, including MySQL, PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to set up your database.

    Let’s look at the installation instructions for:

    • Linux (Ubuntu)
    • Windows
    • macOS

    Installing Rails on Linux (Ubuntu)

    We are installing Ruby on Rails on Ubuntu Linux using RVM (Ruby Version Manager). You can also use rbenv, it is also a lightweight Ruby Version Management Tool.

    • RVM Installs Ruby in its own environment. It provides built-in gemset support.
    • On the other hand, rbenv provides an easy installation, it works by shimming Ruby versions into PATH, but requires additional plugins for gemsets.

    Follow the steps given below to install Ruby on Rails using RVM tool.

    Update System Packages

    Start by updating the system package list and upgrading existing packages −

    $ sudo apt update && sudo apt upgrade -y
    

    Install Dependencies

    Install the required dependencies for Ruby and Rails −

    $ sudo apt install -y curl gnupg2 dirmngr git-core zlib1g-dev build-essential \
    libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 \
    libxml2-dev libxslt1-dev libcurl4-openssl-dev software-properties-common \
    libffi-dev
    

    It installs the general development tools, libraries for Rails, XML and HTML Processing, networking and software management.

    You also need to install Node.js. Rails uses Node.js to handle JavaScript assets. Installation of Yarn is optional, used for managing JavaScript dependencies in Rails projects.

    Install the latest version of Node.JS −

    $ curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash 
    $ sudo apt install -y nodejs
    

    Install Ruby Version Manager RVM

    $ gpg2 --keyserver hkp://keyserver.ubuntu.com --recv-keys 
    409B6B1796C275462A1703113804BB82D39DC0E3 
    7D2BAF1CF37B13E2069D6956105BD0E739499BDB
    

    Load RVM into your Shell

    $ source ~/.rvm/scripts/rvm
    

    Install Ruby

    $ rvm install 3.4.1
    $ rvm use 3.4.1--default
    

    Check the Ruby version

    $ ruby -v
    	ruby 3.4.1(2024-12-25 revision 48d4efcb85)+PRISM[x86_64-linux]

    Installation using rbenv

    If you prefer using rbenv, then install rbenv and ruby-build &minus

    $ git clone https://github.com/rbenv/rbenv.git ~/.rbenv
    $ echo 'export PATH="$HOME/.rbenv/bin:$PATH"'>>~/.bashrc
    $ echo 'eval "$(rbenv init -)"'>>~/.bashrc
    $ source ~/.bashrc
    $ git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
    

    Now, install Ruby −

    $ rbenv install 3.2.2
    $ rbenv global 3.2.2

    Verify the Ruby version −

    $ ruby -v
    	ruby 3.4.1(2024-12-25 revision 48d4efcb85)+PRISM[x86_64-linux]

    Install Bundler

    Bundler is used to manage gems in Rails projects −

    $ gem install bundler
    Fetching bundler-2.6.3.gem
    Successfully installed bundler-2.6.31 gem installed
    

    You can now install Rails

    $ gem install rails
    

    Verify the installation

    $ rails -v
    Rails8.0.1

    Installing Rails on Windows

    The recommended way to install Ruby on Rails on Windows is to use the Windows Subsystem for Linux (WSL). Alternately, you can install Ruby by Using RubyInstaller for Windows and then install Rails on it.

    Installation Using WSL

    Windows Subsystem for Linux (WSL) is a new feature of Microsoft Windows with which you can use a Linux environment without the need for a separate virtual machine or dual booting. WSL is installed by default in Windows 11. It can also be enabled on Windows 10 by turning on the Virtual Machine Platform.

    Open PowerShell or Windows Command Prompt and run −

    $ wsl --install --distribution Ubuntu-24.04

    You may need to reboot during the installation process. You can now open Ubuntu from the Start menu. Enter a username and password for your Ubuntu user when prompted.

    To run a command as administrator (user "root"), use "sudo <command>".See"man sudo_root"for details.Welcome to Ubuntu24.04.1LTS(GNU/Linux5.15.167.4-microsoft-standard-WSL2 x86_64)
    
    lathkar@GNVBGL3:~$
    

    You can now install Ruby and Ruby on Rails, by following the steps explained in the previous section (Installation on Ubuntu Linux)

    Installation Using RubyInstaller

    This Method offers a simpler alternative, its a native Windows installation without requiring WSL. Hence you dont need to switch between Windows and WSL. This is especially suitable for smaller projects or learning Rails. RubyInstaller for Windows installs Ruby for system-wide use by default and not a virtual environment (RVM or rbenv)

    Go to the RubyInstaller website and download the recommended version from https://rubyinstaller.org/downloads/. Ruby+Devkit 3.3.7.1 version is a stable version, hence download and install the same.

    Installation Using RubyInstaller

    During installation, ensure the MSYS2 development toolchain option is selected. MSYS2 is a software distribution and development environment for Windows that provides a minimal Linux-like shell and a package management system.

    After the wizard steps are completed, the command terminal open up and asks you to install MSYS2 and MINGW toolchains.

    RubyInstaller

    You should run the ridk enable command before installing Rails when using RubyInstaller on Windows. This step ensures that the MSYS2 development toolchain and its environment are properly set up, allowing Ruby and Rails to work seamlessly.

    C:\Users\mlath>ridk enable
    

    Now you can install Rails using the gem install rails command −

    Gem Install Rails

    Check the Rails version −

    C:\Users\mlath>rails -v
    Rails8.0.1

    Installing Rails on MacOS

    The macOS environment is very much like Unix. You need to install Xcode Command Line Tools, which include essential tools like git and make.

    xcode-select install
    

    Install Homebrew

    Homebrew is a package manager for macOS that simplifies installing software.

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

    The subsequent steps of installation of RVM/rbenv, Ruby and Rails are similar to those explained in the installation of Ubuntu Linux section.

    Installation Verification

    After performing the installation by following the steps explained above, you can test the installation by creating a new Rails app with the following command −

    $ rails new myapp
    
    Installation Verification

    Navigate into the app directory −

    cd myapp
    

    Start the Rails server with the following command −

    bin/rails server
    

    Visit http://localhost:3000 in your browser to see the Rails welcome page.

    Installation Verification

    To stop the server, press “Ctrl + C”.

    ^C-Gracefully stopping, waiting for requests to finish
    === puma shutdown:2025-01-2700:48:24+0530===-Goodbye!Exiting

    You have thus successfully installed Ruby on Rails on your system.

  • Introduction

    What is Ruby?

    Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base of Rails.

    Ruby is the successful combination of −

    • Smalltalk’s conceptual elegance,
    • Python’s ease of use and learning, and
    • Perl’s pragmatism.

    Ruby is −

    • A high-level programming language.
    • Interpreted like Perl, Python, Tcl/TK.
    • Object-oriented like Smalltalk, Eiffel, Ada, Java.

    Why Ruby?

    Ruby originated in Japan and now it is gaining popularity in US and Europe as well. The following factors contribute towards its popularity −

    • Easy to learn
    • Open source (very liberal license)
    • Rich libraries
    • Very easy to extend
    • Truly object-oriented
    • Less coding with fewer bugs
    • Helpful community

    Although we have many reasons to use Ruby, there are a few drawbacks as well that you may have to consider before implementing Ruby −

    • Performance Issues − Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages like C or C++.
    • Threading model − Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads.

    Sample Ruby Code

    Here is a sample Ruby code to print “Hello Ruby”

    # The Hello ClassclassHellodefinitialize( name )@name= name.capitalize
       enddefsalute
    
      puts "Hello #{@name}!"endend# Create a new object
    h =Hello.new("Ruby")# Output "Hello Ruby!" h.salute

    Output − This will produce the following result −

    Hello Ruby!
    

    Embedded Ruby

    Ruby provides a program called ERB (Embedded Ruby), written by Seki Masatoshi. ERB allows you to put Ruby codes inside an HTML file. ERB reads along, word for word, and then at a certain point, when it encounters a Ruby code embedded in the document, it starts executing the Ruby code.

    You need to know only two things to prepare an ERB document −

    • If you want some Ruby code executed, enclose it between <% and %>.
    • If you want the result of the code execution to be printed out, as a part of the output, enclose the code between <%= and %>.

    Here’s an example. Save the code in erbdemo.rb file. Note that a Ruby file will have an extension .rb −

    <% page_title ="Demonstration of ERB"%>
    <% salutation = "Dear programmer," %><html><head><title><%= page_title %></title>
       </head>
    	
       <body>
    
      &lt;p&gt;&lt;%= salutation %&gt;&lt;/p&gt;&lt;p&gt;This is an example of how ERB fills out a template.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Now, run the program using the command-line utility erb.

    tp> erb erbdemo.rb
    

    This will produce the following result −

    <html><head><title>Demonstration of ERb</title></head><body><p>Dear programmer,</p><p>This is an example  of how ERb fills out a template.</p></body></html>

    What is Rails?

    • An extremely productive web-application framework.
    • Written in Ruby by David Heinemeier Hansson.
    • You could develop a web application at least ten times faster with Rails than you could with a typical Java framework.
    • An open source Ruby framework for developing database-backed web applications.
    • Configure your code with Database Schema.
    • No compilation phase required.

    Full Stack Framework

    • Includes everything needed to create a database-driven web application, using the Model-View-Controller pattern.
    • Being a full-stack framework means all the layers are built to work seamlessly together with less code.
    • Requires fewer lines of code than other frameworks.

    Convention over Configuration

    • Rails shuns configuration files in favor of conventions, reflection, and dynamic runtime extensions.
    • Your application code and your running database already contain everything that Rails needs to know!

    Rails Strengths

    Rails is packed with features that make you more productive, with many of the following features building on one other.

    Metaprogramming

    Where other frameworks use extensive code generation from scratch, Rail framework uses Metaprogramming techniques to write programs. Ruby is one of the best languages for Metaprogramming, and Rails uses this capability well. Rails also uses code generation but relies much more on Metaprogramming for the heavy lifting.

    Active Record

    Rails introduces the Active Record framework, which saves objects into the database. The Rails version of the Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming.

    Convention over configuration

    Most web development frameworks for .NET or Java force you to write pages of configuration code. If you follow the suggested naming conventions, Rails doesn't need much configuration.

    Scaffolding

    You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you'll need.

    Built-in testing

    Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility.

    Three environments

    Rails gives you three default environments: development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run.

  • Ruby on Rails Tutorial

    Ruby on Rails is an extremely productive web application framework written in Ruby. This tutorial gives you a complete understanding on Ruby on Rails.

    What is Ruby on Rails?

    Ruby on Rails (or simply Rails) is a server-side web framework. It follows the MVC (model view controller) pattern for the application development. It is written in Ruby programming language.

    Rails is a full-stack framework that comes with all the tools that facilitate rapid application development. In addition to the web apps, Rails is also used in developing APIs and SaaS (software-as-a-service) applications.

    Ruby on Rails Features

    Some of the important features of Rails are as follows −

    MVC

    MVC stands for Model-View-Controller. It is a well-known software architectural pattern that enables the separation of concerns in an application and hence it makes the code easier to understand and maintain.

    CoC: Convention over Configuration

    Rails follows a set of naming conventions, which allows you to focus on solving business-specific problems. For example, if your code has a model called Employee, Rails associates with the employee table, thus it becomes easier to query the database without explicitly writing SQL queries.

    DRY: Don’t repeat yourself

    Rails follows this established principle in software development, whereby the repetition of same piece of code or information is avoided.

    Scaffolding

    Rails provides this useful feature which lets you generate a standard structure of the project and autogenerates the models, its controllers and the corresponding views for a given resource in a single operation. It is an important feature that greatly contributes to the rapid application development.

    Testing

    Testing the application is an important aspect of web development. Rails offers testing tools such as RSpec and Minitest.

    Installing Ruby on Rails

    Rails can be installed on Windows, Linux as well as MacOS operating systems.

    To develop a Rails application, you need to have Ruby installed on your system, which you can download from https://rubyinstaller.org/downloads/ (for Windows) or for Linux and MacOS, use the gem install command for the purpose.

    Note that you may need to install certain dependencies for Linux and MacOS installation. You can also install Ruby as well as Rails in WSL if using the latest versions of Windows.

    Getting Started with Ruby on Rails

    Make sure that you have installed Ruby and Ruby on Rails on your machine. Create a new Rails app with the following command −

    rails new myapp
    

    Change to the myapp directory and run the following command to create a controller named index and action named index.

    rails generate controller index index
    

    Create a new file in the src folder with the name index_controller.rb and add the index action.

    classIndexController<ApplicationControllerdefindexendend

    Create a Rails template with name index.html.erb and add the following code −

    <h1>Hello World</h1>

    Edit the config/routes.rb file and define a route

    Rails.application.routes.draw do
       root "index#index"end

    Run the Puma server built-in with the Rails installation

    bin/rails server
    

    Visit the URL https://localhost:3000/ to get Hello world text displayed in the browser.

    What is Ruby on Rails Used for?

    Ruby on Rails is used to build web applications and services. It is employed in developing eCommerce sites, social media platforms and other custom web applications. Rails finds its use in building Software as a service (SaaS) application.

    Because of its ease of use and open-source licensing, it is adapted by the startups. An active community of Rails developers is also one of its advantages.

    Who Invented Ruby on Rails?

    David Heinemeier Hansson, a Danish programmer, entrepreneur, and writer is credited as the creator of Ruby on Rails. He extended his work on the project management tool Basecamp into this framework. Hansson first released Rails as open source in July 2004. In 2007, Apple shipped this framework with Mac OS X v10.5 “Leopard”.

    Rails is distributed under the MIT license. https://rubyonrails.org/ is the official website for Ruby on Rails. Its latest version 8.0.1 was released in December 2024.

    How to Check Rails Version?

    To check the Rails version, open a command terminal of your operating system and use the command −

    rails -v
    

    This will display the version of Rails software installed on your system.

    How to Learn Rails?

    Start by setting up your Development environment with Ruby and Rails installed. An extensive Ruby on Rails Guide is available on https://guides.rubyonrails.org/index.html. You can learn Ruby on Rails with the help of several online tutorials including the one at Ruby on Rails.

    Like with any technology, it always helps to keep practicing by building simple projects to reinforce your understanding, gradually adding more advanced features as you progress. Rails is frequently updated. Stay in touch with the latest Rails features and employ them by working on real-world projects or contributing to open-source projects to sharpen your skills.

    Disadvantages of Rails

    Ruby on Rails is an opinionated framework which means it guides you into their way of doing things. Due to its “slow” runtime speed, which makes it harder to scale your RoR applications. Another issue is that the frequent updates to the Rails framework make it difficult to maintain compatibility.

    Skills Required for Becoming a Rails Developer

    To become a Rails developer, you will need strong Ruby programming skills, a solid understanding of web development concepts, proficiency in the functioning of MVC framework (on which Rails is built). You also need to be familiar with databases and SQL, and should be able to work with Git.

    Which Companies Use Ruby on Rails?

    Shopify, a leading e-commerce platform that relies heavily on Ruby on Rails for its backend functionality.

    GitHub is built using Ruby on Rails. It is a popular code hosting platform.

    Rails itself was extracted from the project management tool, Basecamp.

    Ruby on Rails is also used by Airbnb, which is a widely popular online accommodation booking system.

    Careers and Opportunities in Ruby and Rails

    Rails is one of the popular web development frameworks. For someone proficient in Rails there are many career opportunities such as a web developer where you’ll be responsible for building and maintaining web applications. A Rails developer is often required to work on both the front-end and back-end of applications. If you prefer focusing on server-side logic, you can specialize as a back-end developer.

    Proficiency in Ruby and Rails along with good knowledge of HTMLCSS, and JavaScript is essential. You should also be comfortable working with databases like PostgreSQL or MySQL. Another desirable skill is Version Control, API design and application testing.

    Who Should Learn Ruby on Rails

    This tutorial has been designed for beginners who would like to use the Ruby framework for developing database-backed web applications.

    Prerequisites to Learn Ruby on Rails

    You need to have a basic knowledge of Ruby and object-oriented programming to understand this tutorial. In addition, you need to be familiar with internet and websites programming in general.