Starting a new Rails application: the first decisions, and which ones you cannot take back
TL;DR
Difficulty: Beginner
A decision costs what it has been copied into: configuration is easy to change, code grows with every feature, data needs a live migration, and links sent to customers can never be recalled.
- Stay on the Rails defaults for tools unless you can name the reason to leave: import maps, Minitest, the generated Dockerfile.
- Use PostgreSQL in production, for its guarantees (an exclusion constraint stops double bookings) and deployment, not for speed.
- Decide the data early and in writing: tenancy, who logs in, money in whole pence with a rounding rule, time stored as UTC, integer ids inside and tokens outside.
- Scaffold the core model, write one system test, deploy in the first week.
Which of the choices you make in the first afternoon of a Rails project will still be with you in five years? This chapter starts a real application on Rails 7.1, a booking system for a chain of bicycle repair workshops, and gives every early decision a reversal cost. The tool you need is one question: where will this decision get copied?
The question behind this chapter
You have chosen Ruby on Rails. Now there is an empty folder, a terminal, and a command with two dozen options. Where do you start, and which of the choices you make in the first afternoon will still be with you in five years?
Most guides answer the first half and skip the second. Every choice looks equally light. It is not: some first decisions take ten minutes to undo a year later, others take weeks, and a few can never be fully undone.
This chapter walks through the start of a new Rails application on Rails 7.1, the current version, from installing Ruby to the first deploy, and gives every early decision a reversal cost, with a simple test for working it out yourself. If you have not read the previous chapter on how a Rails application is structured, start there: it explains the folders and the request cycle this chapter assumes.
I use one invented business throughout, as in the rest of this series. Cogwell Cycles is a chain of six bicycle repair workshops in Sheffield (cogwellcycles.example), run by its founder Hannah. It has 38 mechanics, about 1,150 repair bookings a week and 9,000 active customers, and it is replacing spreadsheets and a rented booking widget with its own web application. Its two developers are Priya, who has four years of Python, and Owen, who has three years of JavaScript and TypeScript with React. In the chapter on how to choose between Django and Rails, they chose Rails for the product. Today they type rails new. The business and the people are made up. The commands and the code are real and run on Rails 7.1.
The copy test: a decision costs what it has been copied into
Here is the one idea I want you to take from this chapter, because it answers "which choices are hard to change later" for any decision, including ones I do not cover.
A decision is expensive to reverse in proportion to how many places it has been copied into, and to how far from your code those places are.
A choice that lives in one configuration line stays easy to change forever. A choice that has been copied into every view is expensive, and gets more expensive with every feature. A choice that has been written into every row of the database needs a data migration on a live system. And a choice that has left your system altogether, a link in an email a customer received last spring, a mobile app installed on 38 phones, cannot be recalled at all.
So before you agonise over an option, ask where it will be copied. I sort the answers into four layers:
- Configuration: one file or one line. Change it, restart, done.
- Code: views, controllers, tests. Grows with every feature you build.
- Data: the shape and content of rows in the database. Changing it means a migration on live data, with a backup and often a maintenance window.
- Outside: links, identifiers and formats that customers, partners or devices already hold. You can add a translation layer, but you can never take them back.
You can write the cost of reversing a decision as a sum over those layers (Foundations: ratios and rates):
where runs over the four layers (configuration, code, data, outside), is the number of places in layer that carry the decision, and is the hours it takes to change one such place safely, including testing.
The model is crude on purpose. Its value is not the number it produces. Its value is that it makes you notice that , and start at zero on day one and only ever grow.
Example: integer ids or UUIDs at Cogwell, on day one and at month six
Rails numbers rows with integer primary keys by default. The alternative is a UUID (universally unique identifier), a 128 bit random value. Suppose Priya and Owen start with integers and decide at month six that they want UUIDs after all. My illustrative estimates, not measurements:
- Configuration: one generator setting, , hours, so 0.5 hours.
- Code: about 60 places that assume a number (fixtures, tests that build URLs, JSON views, a JavaScript controller that parses an id), , hours, so 15 hours.
- Data: the nine tables of the domain model, each with its primary key and every foreign key pointing at it rewritten in a tested migration, , hours, so 36 hours.
- Outside: every "your booking" email already sent contains a URL with an integer id. At 1,150 bookings a week for 26 weeks that is 29,900 links. They cannot be changed, only redirected, so the old lookup has to live forever. Call it redirect layer, hours to build, plus a permanent piece of code nobody may delete.
where each term is from the list above, in the order configuration, code, data, outside.
On day one the same switch costs the first term alone: half an hour. The decision is identical. Only the number of copies changed. That is why the rest of this chapter sorts choices by where they get copied, not by how important they sound.
Before rails new: Ruby, a version manager and one small file
Rails is a Ruby library, so the first thing a new machine needs is Ruby itself. Rails 7.1 needs Ruby 2.7 or later and the official guide recommends the latest version1. The latest is Ruby 3.3.0, released on 25 December 20232. Start a new application on it.
Do not use the Ruby that ships with your operating system. Use a version manager, a small tool that installs several Ruby versions side by side and picks the right one per project. Three common ones:
- rbenv: switches Ruby per folder by reading a file called
.ruby-version, and installs Rubies through its companionruby-build3. - asdf: one tool for many languages (Ruby, Node.js, Python and more), configured in a
.tool-versionsfile. It can also read.ruby-versionif you switch on itslegacy_version_filesetting4. - chruby: deliberately tiny, it only switches between installed Rubies and can switch automatically from
.ruby-version5.
The useful thing is that all three can read the same .ruby-version file, and rails new writes that file for you1. So the version manager is a personal choice of each developer, copied nowhere in the project. By the copy test, it is the least expensive decision in this chapter: zero copies.
Example: Priya and Owen set up their machines
Priya comes from Python, where she used pyenv to switch Python versions. pyenv was forked from rbenv and ruby-build6, so rbenv feels familiar to her straight away. On her Mac:
# Install rbenv and ruby-build with Homebrew
brew install rbenv ruby-build
# Let rbenv hook into the shell (zsh is the macOS default)
echo 'eval "$(rbenv init - zsh)"' >> ~/.zshrc
source ~/.zshrc
# Install Ruby 3.3.0 and make it her default
rbenv install 3.3.0
rbenv global 3.3.0
# Install the Rails command itself
gem install rails -v 7.1.3
Owen wants one tool for Node.js and Ruby, so he uses asdf with the Ruby plugin and adds legacy_version_file = yes to his ~/.asdfrc. Two developers, two tools, one shared .ruby-version. Neither choice touches the repository.
rails new, option by option
rails new generates the whole skeleton of an application: folders, configuration, a Gemfile listing the libraries (Ruby calls them gems), a test setup and a Dockerfile. Most of its options either choose a component or skip one. These are the ones that matter for a first decision, as defined in the Rails 7.1 generator7:
| Option | What it does | Default |
|---|---|---|
--database | Database adapter: sqlite3, postgresql, mysql, trilogy and others | sqlite3 |
--javascript | How JavaScript reaches the browser: importmap, bun, esbuild, rollup, webpack | importmap |
--css | CSS framework or processor: tailwind, bootstrap, bulma, postcss, sass | none |
--asset-pipeline | Serves and fingerprints static files: sprockets or propshaft | sprockets |
--api | A smaller stack with no views, cookies or sessions | off |
--skip-test | No Minitest setup, usually to add RSpec instead | off |
--skip-docker | No Dockerfile, .dockerignore or bin/docker-entrypoint | off |
--skip-action-mailbox and similar | Leave out a framework you do not need yet | off |
Skipping a component you do not need yet is nearly free, because each can be installed later with one command (for example bin/rails action_text:install). Do it freely.
My view: stay on the defaults unless you can name the reason to leave them. The Rails doctrine calls this "the menu is omakase": let the chef choose, so you need not be an expert in every dish8. Every default you keep is one the guides and the next developer already expect. Every default you change is a small debt of explanation.
The database: PostgreSQL in production, and the reason is not speed
The default database is SQLite, a database that lives in a single file next to your application. For learning Rails it is ideal: nothing to install, nothing to configure, and the getting started guide uses it for exactly that reason1.
For a business application that goes into production, I recommend PostgreSQL. The usual argument is performance, and for most small businesses that argument is weak. SQLite's own documentation is fair about this: it allows any number of readers but only one writer at a time, and because a write usually takes milliseconds, writers simply queue up and take turns, which is fine for many situations9.
Example: is Saturday morning a load problem for Cogwell?
Cogwell's busiest stretch is Friday 6pm to Saturday noon, when 30% of the week's online bookings arrive. How many writes is that (Foundations: ratios and rates)?
where is the booking rate in bookings per hour, is the share of weekly bookings in the peak window, is the number of bookings in a week and is the length of the window in hours (6pm Friday to noon Saturday).
That is about one booking every three minutes. Even if the busiest hour runs at three times the average, that is one a minute. Any database in this chapter handles that without noticing. So load is not the reason to pick PostgreSQL here. There are three better ones.
One: the guarantees you can ask the database for. Rails 7.1 added support for PostgreSQL exclusion constraints10. An exclusion constraint tells the database that no two rows may overlap in a way you define. For a booking system, that is the rule that matters most: one mechanic cannot have two bikes booked for the same time. Validation code in Ruby can check that too, but two customers pressing "book" for the same slot at the same moment can both pass a Ruby check before either has saved. A constraint in the database cannot be raced past.
Two: where the application will run. SQLite stores data in a file on the server's disk. That suits one server with a persistent disk. Many hosting platforms give each container a disk that is wiped on every deploy, and as soon as you run two application servers, they cannot share one file. PostgreSQL runs as its own service that any number of servers can reach.
Three: one service instead of several. Hotwire's live updates, which Cogwell's workshop board will use, travel over Action Cable, Rails' WebSocket framework. In production Action Cable needs a way to pass messages between server processes. The generated configuration uses Redis, but Action Cable also ships a PostgreSQL adapter that uses the database you already have11. One fewer service to run, back up and pay for in the first year.
By the copy test, the database is the most expensive decision on the list. It is copied into the data itself, into every migration, into any SQL you write by hand, and into every constraint like the one below. Switching later means moving every row of a live system.
Example: the double booking constraint in a Cogwell migration
This is the bookings table from Cogwell's first hour (the full sequence comes later in this chapter), with the constraint added by hand:
# db/migrate/20240206090400_create_bookings.rb
class CreateBookings < ActiveRecord::Migration[7.1]
def change
# btree_gist lets one constraint combine "same mechanic" (=)
# with "overlapping time" (&&)
enable_extension "btree_gist"
create_table :bookings do |t|
t.references :mechanic, null: false, foreign_key: true
t.references :customer, null: false, foreign_key: true
t.datetime :starts_at, null: false # stored in UTC
t.datetime :ends_at, null: false
t.integer :quoted_price_pence, null: false, default: 0
t.datetime :cancelled_at
t.timestamps
end
# One mechanic, one bike at a time: the database refuses overlaps
add_exclusion_constraint :bookings,
"mechanic_id WITH =, tsrange(starts_at, ends_at) WITH &&",
using: :gist,
where: "cancelled_at IS NULL",
name: "bookings_no_double_booking"
end
end
Line by line, the parts that are new:
enable_extension "btree_gist"switches on a PostgreSQL extension. An exclusion constraint uses a GiST index, and plain integer equality (mechanic_id WITH =) needs btree_gist to work inside one12.tsrange(starts_at, ends_at)turns the two times into a time range, andWITH &&means "these ranges overlap".where: "cancelled_at IS NULL"limits the rule to live bookings, so a cancelled slot can be booked again.
The Rails guide for PostgreSQL documents exclusion_constraint and range types in full13. Here is a model test that proves the rule holds:
# test/models/booking_test.rb
require "test_helper"
class BookingTest < ActiveSupport::TestCase
test "a mechanic cannot be booked twice for the same time" do
first = bookings(:saturday_service)
clash = Booking.new(mechanic: first.mechanic, customer: first.customer,
starts_at: first.starts_at + 30.minutes,
ends_at: first.ends_at + 30.minutes)
# The database refuses the row; Rails raises StatementInvalid
error = assert_raises(ActiveRecord::StatementInvalid) { clash.save! }
assert_match "bookings_no_double_booking", error.message
end
test "a cancelled booking frees the slot" do
first = bookings(:saturday_service)
first.update!(cancelled_at: Time.current)
rebooked = Booking.new(mechanic: first.mechanic, customer: first.customer,
starts_at: first.starts_at, ends_at: first.ends_at)
assert rebooked.save
end
end
A friendly "that slot has just gone" message for the customer belongs in the controller and the form, which the chapters on Active Record and on Hotwire pick up next. The guarantee is in place from the first hour.
The front end: import maps unless you need a build step
Rails 7.1 offers two ways to get JavaScript into the browser. The default is import maps: the browser loads your JavaScript files directly, as modules, with no Node.js, no bundler and no build step14. The alternative is a bundler through the jsbundling gem: Bun, esbuild, rollup or webpack compile your code into one file before it is served14.
The Rails guide is clear about when you need a bundler: if your code needs a transpilation step, such as JSX or TypeScript, or if you rely on libraries that need webpack style loaders14. The same guide warns that moving from one option to the other may be time consuming for large, complex applications14. Read that warning through the copy test: what gets copied is each JavaScript file. In a Hotwire application, where the server sends HTML and JavaScript only adds small behaviours, there are few such files, and the switch stays affordable for a long time.
CSS is a separate choice. With --css=tailwind and import maps, Rails installs Tailwind through its standalone executable, so there is still no Node.js in the project15. With Bootstrap, Bulma or PostCSS, Rails uses the cssbundling gem, which does need Node.js or Bun. Notice where a CSS framework gets copied: its class names end up in every view, Tailwind's more than most, because its approach is small classes written straight into the HTML. That makes it a code layer decision that grows with every screen.
Example: Owen's TypeScript question
Owen has written TypeScript for three years and asks the obvious question: why give it up? Priya and Owen list the JavaScript the first version actually needs: a Stimulus controller that lets a mechanic drag a job card between "waiting", "in repair" and "ready", one that previews before and after photos, and one that shows free slots as the customer picks a date. Three small files. The live board itself is Turbo Streams, sent from the server.
For three small files, a build step costs more than it gives. They choose import maps, and agree a trigger in writing: if the JavaScript grows past roughly a dozen controllers, or a library they need only ships as TypeScript or JSX, they move to jsbundling with esbuild, and at that size the move is a morning. For CSS they choose Tailwind, knowing it will be copied into every view, because both already know it.
Sprockets or Propshaft: the easiest choice on the list
The asset pipeline serves your static files and stamps each file name with a fingerprint, so browsers can cache them for a long time and still pick up a new version on deploy. Rails 7.1 offers two. Sprockets is the original and still the default7. Propshaft is a newer, much smaller pipeline built for a time when bundling for fewer HTTP connections is no longer urgent: it gives you a load path, digest stamping and a development server, and explicitly leaves compiling to other tools16. Its current version is 0.8.0, from October 202316, so it is still before its 1.0 release.
With import maps and the Tailwind executable, Sprockets' extra machinery has nothing left to do. By the copy test, the choice lives in configuration and a Gemfile line. It costs little either way.
Example: Cogwell picks Propshaft, with one check
Priya and Owen choose Propshaft, because the smaller tool matches what they use. First they check the one thing that could make it expensive: whether any gem they plan for the back office relies on Sprockets. None does. If that changed, going back would take an afternoon.
API only mode, and why it is the wrong start for most products
rails new --api generates a smaller application for serving JSON to other programs. It leaves out the middleware that browsers need, such as cookies, sessions and flash messages, and the generators stop creating views17.
The trap is choosing it because "there will be a mobile app later". A product with a back office, a booking page and a live board has browser users from day one. In API only mode, every one of those screens has to become a separate front end application, with its own login, deployment and tests. Every feature is then built twice, and by the copy test the choice is copied into every controller and every screen from the first day.
A normal Rails application can serve JSON next to its HTML perfectly well. Jbuilder, included by default, builds JSON views7, and the scaffold generator already creates them. API only mode makes sense when there truly is no browser user of Rails' own pages: the only clients are a separate single page application, mobile apps or other services.
Example: the mechanics app, two years early
Cogwell's plan includes a small mobile app for mechanics, later. Hannah asks whether that means an API from the start. It means a few JSON endpoints when the app is built, inside the same application:
# config/routes.rb
Rails.application.routes.draw do
resources :bookings # HTML for staff, JSON for free via jbuilder
# Later, for the mechanics app: versioned JSON next to the HTML
namespace :api do
namespace :v1 do
resources :bookings, only: [:index, :show]
end
end
end
The booking page, the back office and the board stay server rendered HTML with Hotwire. When the app arrives, its controllers live under api/v1. No second application, no second login system.
Minitest or RSpec: taste, and a choice you can change gradually
Rails ships with Minitest as its testing library and generates a test for every model, controller and scaffold you create18. The main alternative is RSpec, through the rspec rails gem, which its own README calls a drop in alternative to Minitest. Its 6.x versions support Rails 7.119.
The difference is mostly style. Minitest tests are plain Ruby classes with assertions such as assert_equal. RSpec uses a describe and it language with expectations such as expect(total).to eq(8500). Both are mature, both are widely used, and both run Rails system tests in a real browser.
By the copy test, the choice is copied into each test file, which sounds expensive. It is not, because the two can live side by side while you move file by file: a gradual decision, not a cliff. The testing series later in this programme covers test driven development in Rails and behaviour driven development with Cucumber, which is how I work myself: tests first, with scenarios a client can read.
Example: Priya and Owen keep the default
Priya knows Python's unittest and pytest. Owen knows Jest, whose describe and it blocks look a lot like RSpec. Instead of arguing for a week, they apply the omakase rule: Minitest is the default, the guides use it, the generators produce it, and if Owen still misses RSpec in three months he can add it next to Minitest. Decision made in five minutes, which is about what it deserves.
The Dockerfile you get for nothing
Since Rails 7.1, every new application comes with a Dockerfile, a .dockerignore and a bin/docker-entrypoint script. The release notes are careful to say these files are meant for deploying to production, not for development20.
The generated Dockerfile is a solid start. It builds in two stages so the final image carries no compilers, runs as a non root user, installs libvips for Active Storage image variants, and its entrypoint runs bin/rails db:prepare before the server starts, so pending migrations are applied on boot21.
You can run that image on any platform that runs containers. Kamal, the deploy tool from 37signals that started life as MRSK and reached version 1.0 in September 2023, deploys it to servers you rent and switches between versions without downtime. The current release is 1.3, and its health check asks the application for /up, a route every new Rails 7.1 application already has22. Platforms such as Heroku, Render or Fly.io are the other common route. By the copy test, hosting lives in one Dockerfile and one deploy configuration: easy to change, unless you come to depend on features only one platform offers.
Example: Cogwell builds its image on day one
Before any feature exists, Priya builds and runs the production image on her laptop:
# Build the production image
docker build -t cogwell .
# Run it against a local PostgreSQL, with the master key for credentials
docker run --rm -p 3000:3000 \
-e RAILS_MASTER_KEY=$(cat config/master.key) \
-e DATABASE_URL=postgres://postgres:secret@host.docker.internal/cogwell_production \
cogwell
Production forces SSL (config.force_ssl = true), so http://localhost:3000/up answers with a redirect to https, which is enough to show the image boots. Ten minutes on day one catches the dull problems, a missing system library or a gem that will not compile on Linux, while the application is too small to hide them.
The decisions that get copied into your data
The table collects every decision in this chapter with its reversal cost. The five that follow it are different from the tool choices above: they are about your data, the layer where the copy test bites hardest. None of them is an option of rails new, which is exactly why they get missed.
| Decision | Cogwell's choice | Where it gets copied | Reversal cost |
|---|---|---|---|
| Database | PostgreSQL | Data, SQL, constraints | High |
| Who is a tenant | Nobody: scope by workshop | Every table and every query | Very high if added late |
| Authentication | has_secure_password for staff | User rows and every controller | Medium: the hashes are portable |
| Money | Whole pence, money rails gem | Every amount column and invoice | High |
| Time zone | London, stored as UTC | Every timestamp, any local time code | Low for data, medium for code |
| Primary keys | Integers inside, tokens outside | Every foreign key, every link sent out | High, and the outside part is permanent |
| Front end approach | Hotwire, server rendered HTML | Every screen | High |
| JavaScript delivery | Import maps | Each JavaScript file | Low while the JavaScript is small |
| CSS framework | Tailwind | Class names in every view | Medium, growing |
| Asset pipeline | Propshaft | Configuration | Low |
| API only mode | No | Middleware and controllers | Medium |
| Test framework | Minitest | Each test file, can coexist | Low and gradual |
| Hosting | Generated Dockerfile | One file and a deploy configuration | Low |
| Ruby version manager | Each developer's own | Nothing in the project | None |
Multi tenancy: a workshop is not a tenant
Multi tenancy means one application serves several separate customers, called tenants, whose data must never mix. There are two common ways to build it in Rails. Row level tenancy puts a tenant id on every table and scopes every query by it, which is what the acts_as_tenant gem does. Schema tenancy gives each tenant its own PostgreSQL schema, a separate set of tables, and needs migrations run against every tenant23.
Adding row level tenancy to an application not built for it means a new column on nearly every table, a backfill of every row, and a review of every query, because one forgotten scope shows one customer another customer's data. By the copy test, it is copied into every table and every query.
So the question has to be asked on day one, and it is a business question, not a technical one: will another company ever log in to this application?
Example: Priya asks Hannah one question
Priya does not ask Hannah about tenancy. She asks: "Could you ever imagine selling this system to another bike repair chain?" Hannah thinks about it and says no: the software is how Cogwell competes, not a product.
So Cogwell's six workshops are not tenants. They are branches of one company, and managers legitimately see across them. A workshop is an ordinary model, mechanics belong to one, and the board filters by workshop with a normal foreign key. Had Hannah said "maybe", the answer would differ: add the tenant now, while it costs a column, not later, when it costs a quarter.
Authentication: decide who logs in before you decide how
Rails 7.1 has the pieces for authentication built in, though no generator assembles them: has_secure_password stores a bcrypt hash of a password, authenticate_by looks a user up and checks the password in one call designed to resist timing attacks, and generates_token_for creates expiring tokens for links such as a password reset24. The widely used alternative is the Devise gem, which bundles registration, confirmation, password recovery, lockout and more into modules25.
Here is the part people miss. Both store passwords as standard bcrypt hashes, and Devise only adds something extra if you configure a pepper25. So the data layer of this decision, the hashes in your users table, is largely portable. What is not portable is the code around login. That makes authentication a medium cost decision, not the high one it feels like.
The decision that really is expensive is who logs in. Staff and customers are different populations with different risks, and in my judgement one users table with a role column for both tends to leak permissions in both directions.
Example: staff log in, customers do not
At Cogwell, the people who log in are staff: 38 mechanics plus the managers. Customers book a slot, receive a confirmation link, and never set a password. That is a product decision: occasional customers will not remember a password, and every stored password is a liability.
So Priya and Owen uncomment bcrypt in the Gemfile and plan a has_secure_password login for staff, with authenticate_by for the sign in. A customer's booking link uses a token, the last decision in this section. The full build is the subject of the chapter on authentication and security in Rails, later in this series.
Money: whole pence from the first migration
Never store money as a floating point number. Floats store most decimal fractions inexactly, which you can see in any Ruby console:
0.1 + 0.2
# => 0.30000000000000004
That error is invisible on one booking and very visible on a year of invoices. The safe options are a decimal column or an integer number of pence. I prefer integers, wrapped by the money rails gem: you name an integer column, and monetize gives you a Money object that knows its currency, formats itself and does arithmetic safely26.
By the copy test, the storage format is copied into every amount column and every stored invoice, so it is a data decision: get it right in the first migration. The gem on top is a code decision, and far easier to change. And there is one setting that is easy to overlook. The money gem rounds half to even by default, often called banker's rounding, and its own code warns that this default will change to half up in its next major version27. Rounding is a business rule. Decide it on purpose and write it down.
Example: a 10% discount on a £12.25 inner tube
Cogwell gives loyal customers 10% off parts. An inner tube costs £12.25, so the discount is 122.5 pence. Half up rounding gives 123 pence. Half to even gives 122 pence, because 122 is even. Neither is wrong, but they are different, and the gem's default is about to change underneath you. So Cogwell's initializer sets it explicitly, after Hannah has checked with her accountant which rule she wants:
# config/initializers/money.rb
MoneyRails.configure do |config|
config.default_currency = :gbp
# A business rule, decided with the accountant: round half up
config.rounding_mode = BigDecimal::ROUND_HALF_UP
# Format amounts from the currency's own rules
config.locale_backend = :currency
end
And in the model:
# app/models/booking.rb (excerpt)
class Booking < ApplicationRecord
# quoted_price_pence holds whole pence, quoted_price returns a Money object
monetize :quoted_price_pence, as: :quoted_price
end
booking.quoted_price.format now returns "£85.00" for an average repair stored as 8500.
Time zones: store UTC, think in London
Rails stores every timestamp in UTC (coordinated universal time) and converts it to the application's time zone when you read it. The setting is config.time_zone, which defaults to UTC, and Active Record's default of :utc for storage applies regardless28. You can list the zone names with bin/rails time:zones.
That means the data layer is safe by default: whatever you set later, the stored values are UTC. What gets copied, and what costs money, is code that ignores the setting. Time.now and Date.today use the server's system time zone, which is usually UTC. Time.current, Time.zone.now and Date.current honour the application's zone, and the Rails guide asks you to prefer them for exactly this reason29. In a booking system, the difference shows up twice a year.
Example: the clocks change on 31 March 2024
In the UK, the clocks go forward on Sunday 31 March 2024. A 9am Saturday slot the day before is 9am GMT, which is 09:00 UTC. The same 9am slot a week later is 9am BST, which is 08:00 UTC. Cogwell sets the zone once:
# config/application.rb (inside the Application class)
config.time_zone = "London"
and pins the behaviour with a test, so nobody can quietly break it:
# test/models/booking_test.rb (one more test)
test "a 9am slot is stored in UTC, whatever the clocks do" do
before_change = Time.zone.parse("2024-03-30 09:00")
after_change = Time.zone.parse("2024-04-06 09:00")
assert_equal 9, before_change.utc.hour # Greenwich Mean Time
assert_equal 8, after_change.utc.hour # British Summer Time
end
If a developer later writes Time.now in the slot finder, the Saturday after the change shows free slots an hour off. The test documents the rule, and the slot finder's own tests will lean on it.
Primary keys: integers inside, tokens outside
Back to the example from the copy test. The argument for UUIDs usually comes down to two worries: integer ids in URLs reveal how many bookings you take (booking 48,210 tells a competitor something), and they can be guessed (change the number in the address bar, see someone else's booking). Rails supports UUID primary keys on PostgreSQL, and the PostgreSQL guide shows how13.
Both worries are about the outside layer, the links you send out. Inside the application, integers serve foreign keys and indexes well, and they are smaller and sort in creation order. So separate the two: integer ids as the identity, an unguessable address for anything that leaves the system. Rails has had a tool for that for years: has_secure_token gives every new record a random token, 24 characters long by default30.
Example: the booking link in Cogwell's confirmation email
Owen adds a token column with the generator's token type, which also adds a unique index:
bin/rails generate migration AddPublicTokenToBookings public_token:token
bin/rails db:migrate
Then the model uses the token wherever a URL is built:
# app/models/booking.rb (excerpt)
class Booking < ApplicationRecord
# Integer id inside the app, an unguessable token in links sent to customers
has_secure_token :public_token
# url_for and the path helpers now put the token in URLs
def to_param
public_token
end
end
And the controller finds bookings by that token:
# app/controllers/bookings_controller.rb (excerpt)
def set_booking
@booking = Booking.find_by!(public_token: params[:id])
end
A booking URL now looks like /bookings/CGY6tf7FXiWRKFxx9n3JML6c. Nothing about volume, nothing to guess, and if Cogwell ever wants UUIDs inside, the links customers hold do not change. By the copy test, for the id decision stays at zero.
Setting up the development environment: bin/setup and bin/dev
Two scripts make a Rails project easy to join. bin/setup is generated with every application. It installs the gems, prepares the database with bin/rails db:prepare, clears old logs and temporary files and restarts the server. The generated file describes itself as idempotent: you can run it at any time and get the same result31. Treat it as living documentation. Whenever the project needs a new step on a fresh machine, the step goes into bin/setup, not into a wiki page.
bin/dev appears when your application needs more than one process in development, for example the Rails server plus the Tailwind watcher that rebuilds CSS when you edit a view. The Tailwind installer creates it together with a Procfile.dev, and it runs both processes through Foreman15.
Example: Owen's first morning on a fresh laptop
git clone git@git.cogwellcycles.example:cogwell.git
cd cogwell
bin/setup # gems, databases, migrations, clean logs
bin/dev # Rails server plus the Tailwind watcher, via Procfile.dev
Three commands from a laptop with Ruby and PostgreSQL to a running application. When Owen hits a missing step, the fix goes into bin/setup, so the next person never does.
The worked example: Cogwell's rails new and Gemfile, every line justified
Here is the whole start, with every decision from the sections above in one place.
rails new cogwell \
--database=postgresql \
--css=tailwind \
--asset-pipeline=propshaft \
--skip-action-mailbox
--database=postgresql: the exclusion constraint, the deploy topology, and Action Cable without Redis.--css=tailwind: both developers know it, and with import maps it installs without Node.js.--asset-pipeline=propshaft: the smaller pipeline is enough once import maps and the Tailwind executable do the rest.--skip-action-mailbox: Cogwell receives no inbound email. One command adds it later if that changes.- No
--javascript: import maps, the default, for three small Stimulus controllers. - No
--api: staff and customers use browsers from day one. - No
--skip-test: Minitest, the default.
The Gemfile, trimmed of comments the generator writes, with one added line per decision:
source "https://rubygems.org"
ruby "3.3.0"
gem "rails", "~> 7.1.3"
gem "propshaft" # asset pipeline: copies and fingerprints files
gem "pg", "~> 1.1" # PostgreSQL in every environment
gem "puma", ">= 5.0" # the web server
gem "importmap-rails" # JavaScript without a build step
gem "turbo-rails" # Hotwire: page updates and the live board
gem "stimulus-rails" # Hotwire: small JavaScript controllers
gem "tailwindcss-rails" # Tailwind via its standalone executable
gem "jbuilder" # JSON views, for the mechanics app later
gem "bcrypt", "~> 3.1.7" # uncommented: has_secure_password for staff
gem "image_processing", "~> 1.2" # uncommented: job card photo variants
gem "money-rails", "~> 1.15" # added: money as whole pence
gem "tzinfo-data", platforms: %i[ windows jruby ]
gem "bootsnap", require: false
group :development, :test do
gem "debug", platforms: %i[ mri windows ]
end
group :development do
gem "web-console"
end
group :test do
gem "capybara"
gem "selenium-webdriver"
end
Notice what is not there: no Redis, no background job library, no authentication gem, no admin framework. Each of those has a later chapter and a reason to wait. A Gemfile on day one should be short enough that a new developer can read every line and know why it is there.
The first hour: three models, one scaffold, seeds and the first system test
With the application generated and bin/setup run, Priya and Owen spend the first hour on the core of the domain. They generate three plain models, then scaffold the one model the first screen needs.
bin/rails generate model Workshop name:string city:string
bin/rails generate model Mechanic workshop:references name:string email:string
bin/rails generate model Customer name:string email:string phone:string
# The core model, with controller, views and tests
bin/rails generate scaffold Booking mechanic:references customer:references \
starts_at:datetime ends_at:datetime quoted_price_pence:integer cancelled_at:datetime
A scaffold generates a model, a migration, a controller with the seven standard actions, HTML and JSON views, routes and tests in one go. It is a starting point to edit, not finished code. Before migrating, Priya edits the bookings migration to add null: false, the default price and the exclusion constraint, exactly as shown in the database section above. Then:
bin/rails db:migrate
The models get their associations and the validations that belong in Ruby. Rails 7.1's normalizes keeps email addresses consistent before they are saved20:
# app/models/workshop.rb
class Workshop < ApplicationRecord
has_many :mechanics, dependent: :restrict_with_error
validates :name, :city, presence: true
end
# app/models/mechanic.rb
class Mechanic < ApplicationRecord
belongs_to :workshop
has_many :bookings, dependent: :restrict_with_error
# Strip spaces and lower case the address before it is saved
normalizes :email, with: ->(email) { email.strip.downcase }
validates :name, :email, presence: true
end
Customer looks the same as Mechanic without the workshop. Booking gets its two belongs_to lines, the monetize and has_secure_token lines from above, and a validation that the end comes after the start.
Example: seeds that can run twice
Seeds are the sample data a developer gets on a fresh machine, loaded with bin/rails db:seed. Write them so they can run any number of times without creating duplicates, because bin/setup and your colleagues will run them more often than you expect:
# db/seeds.rb
# Idempotent: safe to run again with bin/rails db:seed
kelham = Workshop.find_or_create_by!(name: "Cogwell Kelham Island") do |w|
w.city = "Sheffield"
end
sam = kelham.mechanics.find_or_create_by!(email: "sam@cogwellcycles.example") do |m|
m.name = "Sam"
end
alex = Customer.find_or_create_by!(email: "alex@example.com") do |c|
c.name = "Alex"
end
Booking.find_or_create_by!(mechanic: sam, customer: alex,
starts_at: Time.zone.parse("2024-02-10 09:00"),
ends_at: Time.zone.parse("2024-02-10 10:00")) do |b|
b.quoted_price_pence = 85_00 # an average repair, £85
end
Example: the scaffold's own test fails, and that is good news
Fixtures are the test data Rails loads before each test. Priya replaces the generated placeholders with one realistic booking, and does the same for the workshop (kelham), the mechanic (sam) and the customer (alex):
# test/fixtures/bookings.yml
saturday_service:
mechanic: sam
customer: alex
starts_at: 2024-02-10 09:00:00
ends_at: 2024-02-10 10:00:00
quoted_price_pence: 8500
# Fixtures skip model callbacks, so the token is set here
public_token: <%= SecureRandom.base58(24) %>
Then she runs the whole suite with bin/rails test. One test fails:
bin/rails test
# BookingsControllerTest#test_should_create_booking:
# ActiveRecord::StatementInvalid: PG::ExclusionViolation: ERROR:
# conflicting key value violates exclusion constraint "bookings_no_double_booking"
The scaffold's generated test posts a copy of the fixture booking: same mechanic, same time. The database refuses it, exactly as designed. The fix is in the test, not the constraint: book the copy two hours later.
# test/controllers/bookings_controller_test.rb (the create test)
test "should create booking" do
assert_difference("Booking.count") do
post bookings_url, params: { booking: {
mechanic_id: @booking.mechanic_id, customer_id: @booking.customer_id,
starts_at: @booking.starts_at + 2.hours, ends_at: @booking.ends_at + 2.hours,
quoted_price_pence: @booking.quoted_price_pence } }
end
assert_redirected_to booking_url(Booking.last)
end
This is the first useful thing the suite tells them: the generator's assumptions and the business rule disagree, and the business rule wins.
Example: the first system test
A system test drives a real browser through the application, the way a user would. Rails 7.1 generates ApplicationSystemTestCase with Selenium and Chrome, and the scaffold writes a set of system tests for bookings21. Priya replaces them with one test that describes what the first screen is for:
# test/system/bookings_test.rb
require "application_system_test_case"
class BookingsTest < ApplicationSystemTestCase
test "a manager books a Saturday slot" do
visit new_booking_url
# The scaffold's form uses plain id fields; a proper picker comes later
fill_in "Mechanic", with: mechanics(:sam).id
fill_in "Customer", with: customers(:alex).id
fill_in "Starts at", with: Time.zone.parse("2024-02-10 11:00")
fill_in "Ends at", with: Time.zone.parse("2024-02-10 12:00")
fill_in "Quoted price pence", with: 8500
click_on "Create Booking"
assert_text "Booking was successfully created"
end
end
Run it with bin/rails test:system. To run it without a visible browser window, for example on a continuous integration (CI) server, change using: :chrome to using: :headless_chrome in test/application_system_test_case.rb. The test is crude: the form asks for ids, not names. That is fine. It pins the path from an empty form to a saved booking, and every improvement to the form from here on keeps it green.
The first deploy, in the first week
Deploy before there is anything worth showing. The first deploy finds the problems that have nothing to do with features: secrets, the database connection, DNS, email delivery. Each is easy alone and painful next to a launch date.
For Cogwell, two changes come before that first deploy. Action Cable in production switches to the PostgreSQL adapter, so the live board needs no Redis yet11:
# config/cable.yml (production section)
production:
adapter: postgresql
And the production database URL and the Rails master key go into the hosting platform's secret settings, never into the repository. With Kamal 1 that means kamal init to create config/deploy.yml and an environment file, then kamal setup for the first deploy and kamal deploy after that22. On a platform as a service, it means pointing the platform at the Dockerfile.
How long the first deploy takes depends mostly on how many moving parts the first choices added. The chart shows my illustrative estimates for a developer new to Rails, from rails new to a live page. They are judgements, not measurements, and they show the shape: every separate front end, build step or self managed server adds hours before the first feature.
Example: Cogwell's first deploy is a booking form nobody uses
At the end of week one, Cogwell's application is live at a staging address with the booking scaffold, the constraint and the system test. Hannah books a slot for herself, tries to book the same slot again and gets an error page. That error page is the first item on next week's list, a far better problem in week one than in month five.
For the person paying for this
If you are Hannah, you do not need to read the Gemfile. You need five answers, in writing, before the first feature is built. Ask your developers:
- Which database, and why? "PostgreSQL, because the database itself will stop double bookings" is a good answer. "Whatever the default is" is a question to ask again.
- Will another company ever use this? Only you can answer it, and it has to be answered now. Changing it later is the most expensive retrofit on this list.
- Who logs in? Staff, customers, both? Fewer passwords is usually safer and less expensive.
- How is money stored, and how is it rounded? Whole pence, and a rounding rule your accountant has agreed.
- What do the links we send to customers contain? Nothing guessable, and nothing that has to change if the system does.
Then ask for one more thing: a deploy in the first week, even of something trivial. A team that can show you a live, tested booking form after five days has made its first decisions well. It is also how I approach the web applications I build on Rails, where the client owns the code, the accounts and the data from the first commit.
My view: stay on the menu, decide the data early
The choices that feel big at the start, the CSS framework, the asset pipeline, Minitest or RSpec, the hosting platform, are mostly configuration and code. The choices that feel small, a money column, a primary key type, whether a workshop is a tenant, are copied into your data and into the world outside, and their cost grows with every booking.
So my rule for a new Rails application is: stay on the Rails defaults for tools, unless you can name the reason to leave. Make every data decision deliberately, in the first week, in writing. That is what Cogwell did. Its rails new changed four defaults, each for a named reason. Its data decisions, PostgreSQL with a constraint, whole pence with an explicit rounding rule, London time stored as UTC, integers inside and tokens outside, no tenancy because Hannah said so, all fit on one page.
The defaults and their reasons are documented by the Rails team. The copy test and the decision table are my judgement, and you will meet developers who weigh some rows differently: some prefer UUIDs everywhere from the start, some RSpec on day one. Both are defensible. Making those choices by accident is not.
Conclusion
Starting a Rails application well takes an afternoon, not a week. Install Ruby with a version manager, run rails new with as few changed defaults as you can justify, and build the generated Docker image on day one. Then spend your real care on the decisions that get copied into data and into the outside world: the database, tenancy, who logs in, money, time, and what your links contain. When in doubt, use the copy test: count where the decision will be written down, and how far from your code those places are. Scaffold the core model, let the first tests show where the generator and the business disagree, write one system test, and deploy in the first week.
The next chapter, on Active Record, builds out Cogwell's models, migrations and queries on top of exactly this start. The Django series will start the same application in Django later in this programme, so you can compare the first decisions side by side. If you are about to type rails new for your own product, the free workshop is a good place to make these decisions together before the first commit.
