Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 134 ยท Web and Ecosystem

Ruby on Rails Overview

A beginner's guide to Ruby on Rails - what the framework is, MVC, conventions over configuration, routing, controllers, ActiveRecord models, views, generators, plus a runnable mini-MVC in plain Ruby.

Ruby on Rails (usually just "Rails") is a web framework written in Ruby. It is the reason many people first learn Ruby: it made building a database-backed website dramatically faster when it appeared in 2004, and its ideas have been copied by frameworks in nearly every language. GitHub, Shopify, Basecamp and many other large sites run on Rails.

Rails is a big topic that deserves its own tutorial, so this lesson is a guided tour: what the pieces are, how a request travels through them, and what Rails code looks like. One honest limit first. Rails is a third-party gem with many dependencies, and our runner has no network and no Rails installed, so the Rails code on this page is read-only. To make the ideas concrete, we also build a tiny model-view-controller framework in plain Ruby that does run, using only the standard library. The first example shows what happens if you try to use Rails here.

Ruby Rails is not installed on this runner (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The two last lines show the same failure in a different way: Rails is not defined, and the final require ends the script with cannot load such file -- action_controller (LoadError). On your own machine you install Rails with gem install rails (or put gem "rails" in a Gemfile, see RubyGems and Bundler) and it works.

The big ideas

Rails is opinionated. Instead of asking you to decide everything, it picks sensible defaults, and if you follow its conventions you write very little configuration. Two principles explain most of the framework:

  • Convention over configuration. If a model class is called Article, Rails assumes the table is called articles, the controller is ArticlesController, and the views live in app/views/articles/. You only write code where you depart from the convention.
  • Don't repeat yourself (DRY). A fact should live in one place. The database knows the columns of a table, so your model class does not list them again.

Rails also leans on the flexibility of Ruby that you have been learning: its configuration reads like a DSL (see DSLs), it adds methods to classes dynamically (see Metaprogramming), and method_missing-style tricks power things like Article.find_by_title("x").

MVC: three roles

Rails organizes an application into Model, View, Controller:

Part Job Where it lives
Model Data and business rules; talks to the database app/models/article.rb
View The HTML (or JSON) the user sees app/views/articles/show.html.erb
Controller Receives a request, asks models for data, picks a view app/controllers/articles_controller.rb

A request flows like this: the browser asks for GET /articles/42. The router matches the URL and sends it to ArticlesController#show. The controller asks the Article model for record 42, then renders the show view with that record. The resulting HTML is sent back. Each part has one job, which keeps each file small and easy to test.

TEXT
Browser -> Router -> Controller -> Model (database)
                          |
                          v
                        View -> HTML -> Browser

A Rails app in pictures of code

Everything below is a read-only example: you would put these files in a Rails project. Start with creating the project and a scaffold (a generated starting point):

Terminal
# read-only example: needs Rails installed
gem install rails
rails new blog                 # creates the project folder
cd blog
bin/rails generate model Article title:string body:text
bin/rails db:migrate           # creates the articles table
bin/rails generate controller Articles index show
bin/rails server               # starts the app on http://localhost:3000

The model and ActiveRecord

ActiveRecord is Rails' object-relational mapper (ORM): a class stands for a table, an object stands for a row, and attributes stand for columns. You inherit from ApplicationRecord and add rules:

Ruby
# read-only example: app/models/article.rb
class Article < ApplicationRecord
  has_many :comments, dependent: :destroy

  validates :title, presence: true, length: { maximum: 120 }
  validates :body, presence: true

  scope :recent, -> { order(created_at: :desc).limit(10) }

  def summary = body.truncate(80)
end

Using it feels like working with plain Ruby objects, and Rails writes the SQL for you:

Ruby
# read-only example: in `bin/rails console`
article = Article.create!(title: "Hello", body: "My first post")
Article.count                          # SELECT COUNT(*) FROM "articles"
Article.where("title LIKE ?", "H%").first
Article.recent.pluck(:title)
article.update(title: "Hello, Rails")
article.comments.create(author: "Ada", text: "Nice!")
article.destroy

Article.create(title: "")              # invalid: returns an unsaved record
article.errors.full_messages           # => ["Title can't be blank", "Body can't be blank"]

Notice create! raises ActiveRecord::RecordInvalid when validation fails, while create quietly returns an unsaved object. This bang/non-bang pattern is the same convention you saw in Style and Linting. A migration, a Ruby file that changes the database schema over time, creates the table:

Ruby
# read-only example: db/migrate/20260101000000_create_articles.rb
class CreateArticles < ActiveRecord::Migration[8.0]
  def change
    create_table :articles do |t|
      t.string :title, null: false
      t.text :body
      t.timestamps               # created_at and updated_at
    end
  end
end

If you need to learn the SQL behind it, see the SQL tutorial. We return to the ideas of mapping rows to objects in Database access ideas.

Routing

The router lives in config/routes.rb and maps URLs to controller actions. One line, resources :articles, creates all seven standard RESTful routes:

Ruby
# read-only example: config/routes.rb
Rails.application.routes.draw do
  root "articles#index"
  resources :articles do
    resources :comments, only: [:create, :destroy]
  end
  get "/about", to: "pages#about"
end

The resources :articles line expands to this table:

HTTP verb Path Controller#action Purpose
GET /articles articles#index list
GET /articles/new articles#new form for a new record
POST /articles articles#create save a new record
GET /articles/:id articles#show show one
GET /articles/:id/edit articles#edit edit form
PATCH/PUT /articles/:id articles#update save changes
DELETE /articles/:id articles#destroy delete

bin/rails routes prints the real table of your app. These conventions (REST: resources addressed by URL and manipulated by HTTP verbs) are shared by many frameworks.

The controller

A controller is a class whose public methods are actions. Each action gathers data and renders a view. Instance variables (@article) are handed to the view automatically.

Ruby
# read-only example: app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
  def index
    @articles = Article.recent
  end

  def show
    @article = Article.find(params[:id])    # raises RecordNotFound -> 404 page
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article, notice: "Saved."
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def article_params
    params.expect(article: [:title, :body])  # only these fields are allowed
  end
end

The article_params method is a security feature called strong parameters: the controller names exactly which form fields may reach the model, so a malicious user cannot set fields such as admin: true by adding them to the request.

The view

Views are templates written in ERB: HTML with Ruby embedded between <% %> (run code) and <%= %> (run code and insert the result). ERB is part of Ruby's standard library, so you can try it right here:

Ruby ERB, the template language of Rails views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

binding gives the template access to local variables (see Closures and binding). Rails does the same with the instance variables of the controller. Rails also escapes HTML by default in <%= %>, which protects you against cross-site scripting; as the last line shows, plain ERB does not, so use ERB::Util.html_escape yourself outside Rails.

A Rails view for the show action looks like this (read-only):

ERB
<%# read-only example: app/views/articles/show.html.erb %>
<h1><%= @article.title %></h1>
<p><%= simple_format(@article.body) %></p>
<%= link_to "Back to all articles", articles_path %>
<%= link_to "Edit", edit_article_path(@article) %>

articles_path and edit_article_path are route helpers generated from config/routes.rb, so you never write URLs by hand.

A mini MVC framework in plain Ruby

To see how the pieces fit, here is a tiny framework in about sixty lines. It has a router that maps "GET /articles/:id" to a controller action, a model with an in-memory table, a controller with the Rails-style params and instance variables, and ERB views. It is not Rails (no database, no HTTP server, no security), but the shape is the same.

Ruby A tiny MVC framework with ERB views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Follow one request: router.call("GET", "/articles/2") finds the route whose pattern matches (:id became a regex group), builds params as {id: "2"}, creates the controller, calls show (which sets @article), and renders the show view with ERB using the controller's own binding. The two error cases at the end are the Rails 404s: a record that does not exist (RecordNotFound) and a URL without a route (Rails' ActionController::RoutingError). Real Rails adds a lot: a web server speaking HTTP through Rack (see Sinatra and Rack), a database layer, sessions, security protections and much more.

The conventions you saw are the point. In Rails you would not write the Router or the Model class: you write resources :articles and class Article < ApplicationRecord, and the framework supplies the machinery.

What else comes in the box?

Rails is a collection of libraries (they can be used separately) that work together:

  • Active Record (database), Action Controller and Action View (the web layer), and Action Dispatch (routing).
  • Active Support: dozens of helpful extensions to core classes, such as 5.minutes.ago, "hello_world".camelize and blank?/present?. They are monkey patches (see Monkey patching), and they are why Rails code sometimes looks like a slightly different dialect of Ruby.
  • Active Job for background jobs, Action Mailer for email, Active Storage for file uploads, Action Cable for WebSockets.
  • Hotwire (Turbo and Stimulus) for interactive pages without writing much JavaScript, and importmap or other tools for assets.
  • Generators (bin/rails generate ...) that create files with the right names, plus the test framework (Minitest by default; see Minitest).
  • Security defaults: CSRF tokens on forms, SQL-injection safe queries when you use placeholders, HTML escaping, and strong parameters.

When to choose Rails, and what to watch for

Rails is a strong choice when you want to ship a conventional, database-backed web application quickly, with a large ecosystem of gems and a lot of documented practice. It is less suited to tiny single-purpose services (Sinatra or plain Rack is lighter), or to teams that want a very different architecture.

A few things trip up newcomers:

  • N+1 queries. Looping over Article.all and calling article.comments runs one query per article. Use Article.includes(:comments) to load them together.
  • Fat controllers and fat models. Business logic that does not belong to either should move into small plain Ruby classes (service objects, form objects).
  • Magic. Because so much happens by convention, "where does this method come from?" can be hard. Learn to use bin/rails console, bin/rails routes, method(:x).source_location, and read the framework source.
  • Upgrading. Rails versions move fast; keep your app on a supported release and read the upgrade guides. Which Rails supports which Ruby is listed in the release notes (see Ruby versions).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In MVC, which part receives the request and decides what to render?

    The router sends the request to a controller action. The controller asks models for data and picks a view to render.
  2. 2. What does 'convention over configuration' mean in Rails?

    By following naming conventions you get routes, tables, view folders and more without configuring each one.
  3. 3. What does resources :articles in config/routes.rb do?

    It maps index, new, create, show, edit, update and destroy to the standard URLs and HTTP verbs.
  4. 4. What is the difference between Article.create and Article.create! when validation fails?

    The bang version raises on failure, while the plain version quietly returns the invalid, unsaved object.
  5. 5. Why does this site show Rails code only as read-only examples?

    Rails is a third-party gem with many dependencies; require 'rails' raises LoadError here. ERB, however, is standard and runs.

Summary

  • Rails is a full-stack Ruby web framework built on convention over configuration and the MVC pattern.
  • The router maps URLs to controller actions; controllers fetch models and render views; models (Active Record) map classes to database tables.
  • resources :articles generates the seven standard RESTful routes; strong parameters protect which fields may be set.
  • Views are ERB templates: <%= %> inserts a value and Rails escapes HTML by default. ERB is in the standard library and runs everywhere.
  • Rails bundles jobs, mail, storage, WebSockets, Hotwire, generators and tests, and extends core classes through Active Support.
  • Watch for N+1 queries, bloated controllers and models, and framework magic; keep Rails and Ruby versions current.

Next: Sinatra and Rack