Web frameworks · Beginner · 30 min
Build your first Rails 8.1 app with SQLite
By Padding · Updated 18 Nov 2026
Ruby 4.0.10 (ruby:4.0-slim) · Rails 8.1.4.1 · SQLite
You will build a small club-membership app in Rails 8.1 on Ruby 4.0, with two models joined by a has_many association, validations, hand-written routes and controllers, views built from partials, a passing test suite and a clear picture of what Solid Queue and Solid Cache do in production.
On this page
Rails is a full-stack Ruby framework. One command gives you a project with a database layer (Active Record), routing, controllers, HTML templates, a test framework, background jobs, caching, asset handling and a deployment setup, all wired together by convention. Files go in agreed places and follow agreed names, so Rails can find them without configuration. Learning Rails is mostly learning those conventions.
Since Rails 8, a new app uses SQLite for everything, in production as well as on your laptop. Background jobs, the cache and WebSocket messages are stored in their own SQLite databases through three Rails gems (Solid Queue, Solid Cache and Solid Cable), so a small app needs no Redis and no separate database server.
In this tutorial you build Clubhouse, a club-membership app. Visitors see a list of clubs, start a new one, open a club page and join it with their name and email. You generate the models and empty controllers with Rails generators, then write the controllers, routes and views yourself rather than letting the scaffold generator write everything, so you see each part. You need Ruby 4.0; if you have not installed it, follow Hello World in Ruby first.
Step 1 · Install the build tools and Rails
Some gems a Rails app depends on include C code that is compiled when the gem is installed, so you need a compiler and a few headers. On Ubuntu, install them with apt:
sudo apt-get update
sudo apt-get install -y build-essential git libyaml-dev pkg-config curlOn macOS, install Apple's command line tools instead. Ruby built with mise already has the libraries it needs:
xcode-select --installNow install Rails itself. It is a gem like any other. The version is pinned so that what you see matches this page, and --no-document skips building the local API docs, which saves time and data:
ruby --version
gem install rails -v 8.1.4.1 --no-document
rails --versionCheck it worked
ruby --version starts with ruby 4.0, and rails --version prints Rails 8.1.4.1. If your shell says rails: command not found after a successful install, open a new terminal so it picks up the folder where gem puts executables.
Step 2 · Create the app and read the folder layout
Make a throwaway folder and create the app inside it. rails new writes the project, then runs bundle install to download every gem in the new Gemfile, which takes a few minutes the first time:
mkdir -p ~/rails-demo
cd ~/rails-demo
rails new clubhouse
cd clubhouse
lsYou did not pass a database option, so the app uses SQLite. The parts you work with in this tutorial are:
app/holds your code:models/,controllers/andviews/, plushelpers/,jobs/,mailers/,javascript/andassets/.config/routes.rbmaps URLs to controller actions.config/database.ymlsays where each database lives.db/holds migrations (the scripts that change the database) andschema.rb, the current shape of the database.storage/holds the SQLite database files themselves.test/holds tests, andbin/holds the commands you run, such asbin/rails.
You also get a Dockerfile, a Kamal deployment file in config/deploy.yml and config/master.key, the key that decrypts the app's encrypted credentials. The generated .gitignore keeps config/master.key out of git (its pattern is /config/*.key, which covers every key file); never commit it or paste it anywhere.
sed -n '/^development:/,/^test:/p' config/database.ymlCheck it worked
ls lists something like Dockerfile, Gemfile, Gemfile.lock, README.md, Rakefile, app, bin, config, config.ru, db, lib, log, public, script, storage, test, tmp and vendor. The sed command prints the development block of database.yml, which uses the sqlite3 adapter and the file storage/development.sqlite3.
Step 3 · Start the development server
In your second terminal, go to ~/rails-demo/clubhouse and start the server:
bin/rails serverThe server is Puma, listening on port 3000 of your own machine only. In development, Rails reloads your code on the next request after you save a file, so you can leave the server running for the rest of the tutorial. Back in the first terminal, ask for the home page and the health check:
curl -s http://localhost:3000/ | grep -o '<title>[^<]*</title>'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/upCheck it worked
The first command prints <title>Ruby on Rails 8.1.4.1</title>: with no home page of its own yet, the app shows the Rails welcome page. Open http://localhost:3000/ in a browser to see it, with the Rails and Ruby versions near the bottom. The second command prints 200. /up is a health check route that every new app has; it answers 200 when the app boots without errors, which load balancers and uptime monitors use.
Step 4 · Generate the Club and Member models
A model is a Ruby class backed by a database table. Each club has a name and a description, and each member belongs to one club. The model generator writes the class, a migration that creates the table, a test file and a fixtures file:
bin/rails generate model Club name:string description:text
bin/rails generate model Member club:references name:string email:stringOpen the newest file in db/migrate/. Its name starts with a timestamp and ends in _create_members.rb. The club:references field became this line:
t.references :club, null: false, foreign_key: trueThat adds a club_id column that cannot be empty, an index on it and a foreign key, so SQLite refuses a member that points at a club that does not exist. Run the migrations to create both tables:
bin/rails db:migrate
grep -n 'create_table' db/schema.rbCheck it worked
db:migrate prints one CreateClubs: migrated and one CreateMembers: migrated line. The grep prints two lines from db/schema.rb, create_table "clubs" and create_table "members". Rails rewrites schema.rb after every migration, so it always shows the current shape of the database; never edit it by hand.
Step 5 · Add validations and the has_many association
The generator gave Member a belongs_to :club line, but Club knows nothing about its members yet, and neither model checks its data. Replace app/models/club.rb:
cat > app/models/club.rb <<'RUBY'
class Club < ApplicationRecord
has_many :members, dependent: :destroy
validates :name, presence: true, length: { maximum: 80 },
uniqueness: { case_sensitive: false }
validates :description, length: { maximum: 500 }
end
RUBYhas_many :members gives every club a members method that returns its members and can build new ones. dependent: :destroy deletes a club's members when the club is deleted, instead of leaving rows that point at nothing. Now replace app/models/member.rb:
cat > app/models/member.rb <<'RUBY'
class Member < ApplicationRecord
belongs_to :club
normalizes :email, with: ->(email) { email.strip.downcase }
validates :name, presence: true, length: { maximum: 80 }
validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP },
uniqueness: { scope: :club_id }
end
RUBYnormalizes cleans the email as soon as it is assigned, so Ngozi@Example.com ` and `ngozi@example.com count as the same address. uniqueness: { scope: :club_id } allows one email once per club, so the same person can still join several clubs. belongs_to also adds a validation of its own: a member without a club is invalid.
Uniqueness validations run a query before saving, so two requests arriving at the same moment can both pass. On a busy site, back them with a unique index in a migration as well.
Try the models from the command line. bin/rails runner loads the app and runs a piece of Ruby against the development database:
bin/rails runner '
club = Club.create!(name: "Lagos Chess Club", description: "Saturday games at the library.")
club.members.create!(name: "Ngozi Okafor", email: " Ngozi@Example.com ")
copy = club.members.build(name: "Copy", email: "NGOZI@example.com")
puts copy.valid?
puts copy.errors.full_messages.inspect
puts Club.new.tap(&:validate).errors.full_messages.inspect
puts club.members.count
puts Member.last.email
'Check it worked
The runner prints five lines: false, ["Email has already been taken"], ["Name can't be blank"], 1 and ngozi@example.com. The duplicate member was never saved, and the stored address is trimmed and lower case. The club and Ngozi stay in the development database, so you will see them in the browser shortly.
Step 6 · Add routes and controllers
Routes connect URLs to controller actions. Generate two empty controllers. With no action names after the controller name, the generator adds no routes, which you write yourself next:
bin/rails generate controller Clubs
bin/rails generate controller MembersEach command creates a controller file, a folder for its views, a helper and a test file. Replace config/routes.rb:
cat > config/routes.rb <<'RUBY'
Rails.application.routes.draw do
get "up" => "rails/health#show", as: :rails_health_check
resources :clubs, only: %i[index show new create] do
resources :members, only: %i[create]
end
root "clubs#index"
end
RUBYresources :clubs declares the standard set of routes for clubs, and only: keeps the four this app needs. Nesting members inside clubs gives the join form the URL /clubs/:club_id/members, so the controller always knows which club the new member is joining. root makes the club list the home page. Write the clubs controller in app/controllers/clubs_controller.rb:
cat > app/controllers/clubs_controller.rb <<'RUBY'
class ClubsController < ApplicationController
def index
@clubs = Club.includes(:members).order(:name)
end
def show
@club = Club.find(params.expect(:id))
@members = @club.members.order(:name)
@member = Member.new
end
def new
@club = Club.new
end
def create
@club = Club.new(club_params)
if @club.save
redirect_to @club, notice: "#{@club.name} is ready for members."
else
render :new, status: :unprocessable_content
end
end
private
def club_params
params.expect(club: [ :name, :description ])
end
end
RUBYInstance variables set in an action, such as @clubs, are passed to that action's view. Club.find raises an error for an unknown id, which Rails turns into a 404 page. params.expect accepts only the fields you list from the form, so a visitor cannot set other columns by adding fields to the request. After a successful save, the action redirects, so reloading the page does not submit the form again. A failed save shows the form again with status 422. The includes(:members) in index loads every club's members in one extra query rather than one query per club.
Now app/controllers/members_controller.rb:
cat > app/controllers/members_controller.rb <<'RUBY'
class MembersController < ApplicationController
def create
@club = Club.find(params.expect(:club_id))
@member = @club.members.build(member_params)
if @member.save
redirect_to @club, notice: "#{@member.name} joined #{@club.name}."
else
@members = @club.members.order(:name)
render "clubs/show", status: :unprocessable_content
end
end
private
def member_params
params.expect(member: [ :name, :email ])
end
end
RUBY
bin/rails routes -g clubWhen joining fails, the action renders the club page again, so the visitor sees the errors next to the form they filled in.
Check it worked
bin/rails routes -g club lists the routes that mention clubs, something like clubs GET /clubs(.:format) clubs#index, POST /clubs(.:format) clubs#create, new_club GET /clubs/new(.:format) clubs#new, club GET /clubs/:id(.:format) clubs#show and club_members POST /clubs/:club_id/members(.:format) members#create. The first column is the name of the route helper: club_members becomes club_members_path(club) in your code.
Step 7 · Build the views from partials
Views are ERB files: HTML with Ruby inside <%= %> tags, which print a value, and <% %> tags, which run code without printing. Rails escapes everything printed with <%= %>, so text a visitor typed shows as text and never runs as a script.
First, replace the layout that wraps every page, adding a spot for the notice message that the controllers set:
cat > app/views/layouts/application.html.erb <<'ERB'
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= content_for(:title) || "Clubhouse" %></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<main>
<% if notice %>
<p class="notice"><%= notice %></p>
<% end %>
<%= yield %>
</main>
</body>
</html>
ERByield is where each page's own view goes. A partial is a view fragment whose file name starts with an underscore. Rails has a convention for them: render @clubs renders app/views/clubs/_club.html.erb once for each club, with the club in a local variable called club. Write the club list and its partial:
cat > app/views/clubs/index.html.erb <<'ERB'
<% content_for :title, "Clubs" %>
<h1>Clubs</h1>
<p><%= link_to "Start a club", new_club_path %></p>
<ul class="clubs">
<%= render(@clubs) || tag.li("No clubs yet.") %>
</ul>
ERB
cat > app/views/clubs/_club.html.erb <<'ERB'
<li id="<%= dom_id(club) %>">
<%= link_to club.name, club %>
<span class="count"><%= pluralize(club.members.size, "member") %></span>
</li>
ERBrender returns nil for an empty collection, so the || shows a placeholder instead. dom_id(club) gives each item an id such as club_1. Both forms in the app show validation errors the same way, so that markup goes in a shared partial that takes the record as a local:
mkdir -p app/views/shared
cat > app/views/shared/_errors.html.erb <<'ERB'
<% if record.errors.any? %>
<div class="errors" role="alert">
<p><%= pluralize(record.errors.count, "problem") %> stopped this from saving:</p>
<ul>
<% record.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
ERB
cat > app/views/clubs/new.html.erb <<'ERB'
<% content_for :title, "Start a club" %>
<h1>Start a club</h1>
<%= form_with model: @club do |form| %>
<%= render "shared/errors", record: @club %>
<%= form.label :name %>
<%= form.text_field :name, required: true, maxlength: 80 %>
<%= form.label :description %>
<%= form.text_area :description, rows: 3, maxlength: 500 %>
<%= form.submit "Create club" %>
<% end %>
ERBform_with model: @club works out the URL and method from the record: a new club posts to /clubs. It also adds a hidden authenticity_token field, which Rails checks on every form submission to block cross-site request forgery. Now the club page, the member partial and the join form:
cat > app/views/clubs/show.html.erb <<'ERB'
<% content_for :title, @club.name %>
<p><%= link_to "All clubs", clubs_path %></p>
<h1><%= @club.name %></h1>
<p><%= @club.description %></p>
<h2>Members</h2>
<ul class="members">
<%= render(@members) || tag.li("No members yet.") %>
</ul>
<h2>Join this club</h2>
<%= render "members/form", club: @club, member: @member %>
ERB
cat > app/views/members/_member.html.erb <<'ERB'
<li id="<%= dom_id(member) %>"><%= member.name %></li>
ERB
cat > app/views/members/_form.html.erb <<'ERB'
<%= form_with model: [club, member] do |form| %>
<%= render "shared/errors", record: member %>
<%= form.label :name %>
<%= form.text_field :name, required: true, maxlength: 80 %>
<%= form.label :email %>
<%= form.email_field :email, required: true %>
<%= form.submit "Join" %>
<% end %>
ERBform_with model: [club, member] builds the nested URL /clubs/1/members. The member partial shows names only: email addresses stay in the database and never appear on a public page. Finally, a little CSS. Rails serves everything in app/assets/stylesheets/ through the stylesheet_link_tag :app line in the layout:
cat > app/assets/stylesheets/application.css <<'CSS'
body { font-family: system-ui, sans-serif; line-height: 1.5; max-width: 40rem; margin: 2rem auto; padding: 0 1rem; }
.notice { background: #e9f2ec; padding: 0.5rem 0.75rem; }
.errors { color: #a1260d; }
.count { color: #5c6168; }
label, input, textarea { display: block; font: inherit; }
input[type="text"], input[type="email"], textarea { width: 100%; margin-bottom: 0.75rem; }
CSS
curl -s http://localhost:3000/ | grep -E 'Lagos Chess Club|member'
curl -s http://localhost:3000/clubs/1 | grep -E '<li|<title>'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/clubs/999Check it worked
The first curl prints the link to Lagos Chess Club and the line <span class="count">1 member</span>. The second prints the title <title>Lagos Chess Club</title> and <li id="member_1">Ngozi Okafor</li>, with no email address anywhere. A club that does not exist returns 404.
Now use the browser at http://localhost:3000/. Open Lagos Chess Club and join it with your own name and an email address. The page reloads with a green line such as Amina joined Lagos Chess Club. and your name in the list. Join again with the same email in capitals: the form comes back with 1 problem stopped this from saving: and Email has already been taken. Names with accents and tone marks, such as Adébáyọ̀, are stored and shown exactly as typed, because Rails and SQLite use UTF-8 throughout. Then follow Start a club and create a second club.
The pages are plain server-rendered HTML with a small stylesheet, so they load quickly on a low-end Android phone and use little prepaid data. Rails also loads Turbo, which swaps in each new page without a full browser reload.
Step 8 · Write tests and run bin/rails test
Rails apps come with Minitest, and the generators already created a test file for each model and controller. Tests run against a separate database, storage/test.sqlite3, which Rails fills from fixtures: YAML files with sample rows. Replace the generated fixtures with data the tests can refer to by name:
cat > test/fixtures/clubs.yml <<'YAML'
chess:
name: Lagos Chess Club
description: Saturday games at the library.
running:
name: Nairobi Running Club
description: Early runs on weekdays.
YAML
cat > test/fixtures/members.yml <<'YAML'
ngozi:
club: chess
name: Ngozi Okafor
email: ngozi@example.com
YAMLclub: chess points the member at the chess fixture; Rails fills in the id. Now the model tests:
cat > test/models/club_test.rb <<'RUBY'
require "test_helper"
class ClubTest < ActiveSupport::TestCase
test "needs a name" do
club = Club.new
assert_not club.valid?
assert_includes club.errors[:name], "can't be blank"
end
test "removes its members when deleted" do
assert_difference("Member.count", -1) { clubs(:chess).destroy }
end
end
RUBY
cat > test/models/member_test.rb <<'RUBY'
require "test_helper"
class MemberTest < ActiveSupport::TestCase
test "normalises the email address" do
member = Member.new(club: clubs(:chess), name: "Kwame", email: " Kwame@Example.COM ")
assert_equal "kwame@example.com", member.email
end
test "rejects an email already used in the same club" do
member = Member.new(club: clubs(:chess), name: "Copy", email: "NGOZI@example.com")
assert_not member.valid?
assert_includes member.errors[:email], "has already been taken"
end
test "allows the same email in a different club" do
member = Member.new(club: clubs(:running), name: "Ngozi Okafor", email: "ngozi@example.com")
assert member.valid?
end
end
RUBYIntegration tests send requests through the whole app, from routing to the rendered HTML, without a browser. assert_select checks the HTML with CSS selectors. Replace the two generated controller tests:
cat > test/controllers/clubs_controller_test.rb <<'RUBY'
require "test_helper"
class ClubsControllerTest < ActionDispatch::IntegrationTest
test "the home page lists clubs with member counts" do
get root_url
assert_response :success
assert_select "ul.clubs li", 2
assert_select "#club_#{clubs(:chess).id} .count", "1 member"
end
test "creating a club redirects to its page" do
assert_difference("Club.count", 1) do
post clubs_url, params: { club: { name: "Kumasi Book Club", description: "Monthly reads." } }
end
assert_redirected_to club_url(Club.find_by!(name: "Kumasi Book Club"))
end
test "a club with no name shows the form again" do
assert_no_difference("Club.count") do
post clubs_url, params: { club: { name: "" } }
end
assert_response :unprocessable_content
assert_select ".errors li", "Name can't be blank"
end
end
RUBY
cat > test/controllers/members_controller_test.rb <<'RUBY'
require "test_helper"
class MembersControllerTest < ActionDispatch::IntegrationTest
test "joining a club adds the member and shows a notice" do
club = clubs(:chess)
assert_difference("club.members.count", 1) do
post club_members_url(club), params: { member: { name: "Adébáyọ̀ Ọlá", email: "ade@example.com" } }
end
assert_redirected_to club_url(club)
follow_redirect!
assert_select "p.notice", "Adébáyọ̀ Ọlá joined Lagos Chess Club."
assert_select "ul.members li", 2
end
test "a duplicate email shows the error and saves nothing" do
assert_no_difference("Member.count") do
post club_members_url(clubs(:chess)), params: { member: { name: "Copy", email: "ngozi@example.com" } }
end
assert_response :unprocessable_content
assert_select ".errors li", "Email has already been taken"
end
end
RUBY
bin/rails testRails switches off the CSRF token check while tests run, so these tests can post without one. In development and production the check stays on.
Check it worked
bin/rails test ends with a line like 10 runs, 25 assertions, 0 failures, 0 errors, 0 skips; the assertion count can differ, but there must be 10 runs and no failures or errors. To see a failure, change "1 member" to "2 members" in clubs_controller_test.rb and run the tests again: Minitest names the test, the file and line, and shows the expected and actual text. Change it back afterwards.
Step 9 · See what Solid Queue and Solid Cache do in production
In development, Rails keeps the cache in memory and runs background jobs in a thread inside the server, which is enough on one laptop. The production settings are different. Look at them:
grep -n 'solid' config/environments/production.rb
sed -n '/^production:/,$p' config/database.yml
ls db/*_schema.rbHere is what those lines set up:
- Solid Cache (
config.cache_store = :solid_cache_store) storesRails.cacheentries instorage/production_cache.sqlite3. A cache on disk can be far bigger than one in memory and survives a restart. - Solid Queue (
config.active_job.queue_adapter = :solid_queue) stores background jobs, such as sending an email after someone joins, instorage/production_queue.sqlite3. Workers pick them up from there. Inconfig/puma.rb, the lineplugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"]lets the web server run the workers itself, so a small app needs one process, not two. - Solid Cable does the same for Action Cable, the WebSocket messages behind live page updates, in
storage/production_cable.sqlite3.
Each database gets its tables from its own schema file (db/cache_schema.rb, db/queue_schema.rb, db/cable_schema.rb), separate from your app's schema.rb. Because all four databases are files in storage/, a production server must keep that folder on a persistent disk and back it up. The generated Kamal config (config/deploy.yml) already mounts it as a volume.
Check it worked
The grep prints lines including config.cache_store = :solid_cache_store, config.active_job.queue_adapter = :solid_queue and config.solid_queue.connects_to = { database: { writing: :queue } }. The sed shows a production: block with four entries, primary, cache, queue and cable, each pointing at its own file in storage/. ls lists db/cable_schema.rb, db/cache_schema.rb and db/queue_schema.rb.
Stop the development server with Ctrl+C in its terminal. If you are going on to add sign-in with the authentication generator, keep the app. Otherwise remove it:
cd ~
rm -rf ~/rails-demoRails itself stays installed as a gem. Remove it with gem uninstall rails if you no longer want it; the gems it depends on stay until you remove them too.
Next steps
- Let members sign in, with sessions and password resets built into Rails: add sign-in with the authentication generator.
- Go back over blocks, objects and Bundler: Hello World in Ruby.
- Compare with Python's batteries-included framework, which has its own admin: create your first Django 6 app.
- See how much a small framework leaves to you: build your first web app with Flask 3.
Part of these paths
Related tutorials
- Hello World in Ruby: irb, puts and a first gem with BundlerYou will install Ruby 4.0, see how puts, print and p differ in irb, run a script that greets the user with a block, and print a table with your first gem managed by Bundler.
- Add sign-in to a Rails app with the built-in authentication generatorYou will have a Rails 8.1 app with sign-in, sign-out and password reset from the built-in generator, a sign-up page you add yourself, a members area that needs a session, a rate-limited login form and integration tests that prove it all works.
- How to Create Your First Django 6 AppYou will create a Django 6.1 project with uv on Python 3.15, build a small bookmarks app with a database model, an admin screen, a page and a test, and see how the pieces connect.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials