Ruby on Rails basics
Ruby on Rails (or just Rails) is the web framework that made Ruby famous. Released in 2004, it popularised ideas every modern framework now uses: convention over configuration, database migrations, and building a full app with a few commands. GitHub, Shopify, Basecamp, GitLab and Zendesk run on Rails, and it's still one of the fastest ways for a small team to build a complete web application.
💡 Rails runs on a server, not in the browser. Every command below was run with Ruby 4.0 on Linux, and its output is shown underneath, so you can follow along on your own computer.
The big ideas
| Idea | Means |
|---|---|
| MVC | Models hold data and rules, Views render HTML, Controllers handle requests |
| Convention over configuration | Name things the Rails way (Article model → articles table → ArticlesController) and everything connects without setup |
| Active Record | Database rows become Ruby objects; you rarely write SQL |
| Migrations | Database changes are Ruby files, versioned in Git |
| Generators | rails generate writes the boilerplate files for you |
Creating an app
gem install rails -v 8.1.4.1 --no-document > /dev/null 2>&1
rails -v
rails new blog --minimal --skip-git --skip-docker --skip-test > /dev/null 2>&1
cd blog
lsRails 8.1.4.1 Gemfile README.md app config db log script tmp Gemfile.lock Rakefile bin config.ru lib public storage vendor
--minimal leaves out optional parts (email, background jobs, front-end tooling) to keep this lesson focused. A default rails new blog includes them, and uses SQLite as the database so there's nothing else to install.
| Folder | Holds |
|---|---|
app/models, app/controllers, app/views |
Your MVC code |
config/routes.rb |
Which URL goes to which controller action |
db/migrate |
Migrations; db/schema.rb is the resulting schema |
Gemfile |
The app's gems |
bin/rails |
The command-line tool for this app |
A model and its migration
Generate an Article model with a title and body:
cd blog
bin/rails generate model Article title:string body:text published:boolean 2>&1 | sed -E 's/[0-9]{14}/YYYYMMDDHHMMSS/'
cat db/migrate/*_create_articles.rb
bin/rails db:migrate 2>&1 | sed -E 's/[0-9]{14}/YYYYMMDDHHMMSS/; s/\([0-9.]+s\)/(0.00Xs)/; s/-> [0-9.]+s/-> 0.00Xs/' invoke active_record
create db/migrate/YYYYMMDDHHMMSS_create_articles.rb
create app/models/article.rb
class CreateArticles < ActiveRecord::Migration[8.1]
def change
create_table :articles do |t|
t.string :title
t.text :body
t.boolean :published
t.timestamps
end
end
end
== YYYYMMDDHHMMSS CreateArticles: migrating ===================================
-- create_table(:articles)
-> 0.00Xs
== YYYYMMDDHHMMSS CreateArticles: migrated (0.00Xs) ==========================The migration is Ruby that describes the change; db:migrate applies it, creating the articles table with id, created_at and updated_at added automatically.
Active Record: working with data
bin/rails runner runs Ruby with the whole app loaded. (In development you'd use the interactive bin/rails console.)
Article.delete_all
Article.create!(title: "Hello Rails", body: "My first post", published: true)
Article.create!(title: "Draft ideas", body: "Not ready yet", published: false)
Article.create!(title: "Active Record", body: "Rows become objects", published: true)
puts "count: #{Article.count}"
puts "published: #{Article.where(published: true).pluck(:title).inspect}"
first = Article.order(:id).first
puts "first: #{first.title} (id #{first.id})"
first.update!(title: "Hello, Rails!")
puts "renamed: #{Article.find(first.id).title}"
puts "search: #{Article.where("title LIKE ?", "%Active%").count}"
puts "SQL: #{Article.where(published: true).order(created_at: :desc).limit(2).to_sql}"cd blog
bin/rails runner script/demo.rbcount: 3 published: ["Hello Rails", "Active Record"] first: Hello Rails (id 1) renamed: Hello, Rails! search: 1 SQL: SELECT "articles".* FROM "articles" WHERE "articles"."published" = TRUE ORDER BY "articles"."created_at" DESC LIMIT 2
where, order and limit build a query lazily; the SQL runs only when you need the results. to_sql shows what Active Record will send to the database. Notice there's no table name or column list anywhere in the Ruby code: the conventions provide them.
Validations and associations
Models hold your business rules:
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true, length: { maximum: 100 }
validates :body, presence: true
scope :published, -> { where(published: true) }
endcd blog
bin/rails generate model Comment article:references author:string body:text > /dev/null 2>&1
bin/rails db:migrate > /dev/null 2>&1
cat app/models/comment.rb
cat > script/rules.rb <<'RUBY'
bad = Article.new(title: "", body: "")
puts "valid? #{bad.valid?}"
puts bad.errors.full_messages
post = Article.published.first
post.comments.create!(author: "Asha", body: "Great post!")
post.comments.create!(author: "Ravi", body: "Thanks")
puts "#{post.title} has #{post.comments.count} comments by #{post.comments.pluck(:author).join(' and ')}"
puts "comment belongs to: #{Comment.first.article.title}"
RUBY
bin/rails runner script/rules.rbclass Comment < ApplicationRecord belongs_to :article end valid? false Title can't be blank Body can't be blank Hello, Rails! has 2 comments by Asha and Ravi comment belongs to: Hello, Rails!
has_many :comments and belongs_to :article (written by the generator because of article:references) give you post.comments, comment.article and more, with no extra code.
Routes, controllers and views
A scaffold generates a complete set of pages (list, show, create, edit, delete) for a resource. It's a good way to see how the pieces connect:
cd blog
bin/rails generate scaffold_controller Article title:string body:text published:boolean --skip-jbuilder > /dev/null 2>&1
cat > config/routes.rb <<'RUBY'
Rails.application.routes.draw do
get "up" => "rails/health#show", as: :rails_health_check
resources :articles
root "articles#index"
end
RUBY
bin/rails routes -c articles 2>/dev/null | sed -E 's/ +$//' Prefix Verb URI Pattern Controller#Action
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root GET / articles#indexWriting resources :articles in config/routes.rb creates the seven standard RESTful routes, each mapped to a controller action. Here's the generated index and create actions:
cd blog
sed -n '/def index/,/^ end/p;/def create/,/^ end/p' app/controllers/articles_controller.rb def index
@articles = Article.all
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article, notice: "Article was successfully created."
else
render :new, status: :unprocessable_content
end
endAnd the view, in app/views/articles/index.html.erb, is HTML with embedded Ruby (<%= … %> prints a value):
<h1>Articles</h1>
<% @articles.each do |article| %>
<h2><%= link_to article.title, article %></h2>
<p><%= article.body %></p>
<% end %>
<%= link_to "New article", new_article_path %>Let's start the server and request the pages:
cd blog
(bin/rails server -p 3000 > /tmp/server.log 2>&1 &)
for i in $(seq 1 30); do curl -s -o /dev/null localhost:3000/up && break; sleep 1; done
curl -s localhost:3000/articles | grep -oE "<h1>[^<]*</h1>|<strong>Title:</strong>|Hello, Rails!|Active Record" | sort -u
curl -s -o /dev/null -w "GET /articles/999 → %{http_code}\n" localhost:3000/articles/999
pkill -f "rails server" || pkill -f puma<h1>Articles</h1> <strong>Title:</strong> Active Record Hello, Rails! GET /articles/999 → 404
The request went route → ArticlesController#index → Article.all → view → HTML. That's the whole Rails cycle. The unknown article gives a 404 because find raises RecordNotFound, which Rails turns into "Not Found".
Where to go next
- The official guide: Getting Started with Rails at guides.rubyonrails.org builds a complete blog and is excellent.
- Hotwire (Turbo and Stimulus), Rails' default way to build interactive pages with very little JavaScript.
- Authentication:
bin/rails generate authentication(Rails 8+) adds sign-in, sessions and password resets. - Background jobs (Solid Queue), caching (Solid Cache) and deployment with Kamal, all included in a default Rails app.
- APIs:
rails new api --apicreates a JSON-only backend for a React or mobile front end.
Practice
- Create a new Rails app and generate a
Productmodel withname:string price:decimal. - Add a validation that
priceis greater than 0 and test it inbin/rails console. - Add a
Reviewmodel thatbelongs_to :product, and show each product's review count. - Add
resources :productsand scaffold the controller and views, then open the pages in your browser.
1.What does "convention over configuration" mean in Rails?
2.What does bin/rails db:migrate do?
3.Which line gives an Article a comments method that returns its comments?
4.What does resources :articles in routes.rb create?