How a Rails application is structured: what goes where, and how a request travels through it

TL;DR

Difficulty: Beginner

A Rails application is a lookup table keyed by a name: call a thing Booking and Rails knows its file, table, controller, templates, URLs and tests.

  • app holds the code that answers requests, config what runs once at boot, db the history of the database, with lib, bin and test around them.
  • A request goes Puma, Rack middleware, router, before actions, controller action, Active Record, view inside the layout, and back out the same way.
  • Sort code by when it runs and you will put it in the right folder.
  • Never accept magic you cannot print: bin/rails routes, middleware, zeitwerk:check and the log show every convention.

Open a new Rails project and you meet a dozen folders and files you never typed. It looks like a maze, and it is closer to a lookup table. Here is what goes where in a Rails 7.1 application, how one request travels through it, and how to print every piece of the so called magic, built on an invented bicycle workshop chain in Sheffield.

The question behind this article

Priya opens the new project on her laptop and sees a dozen folders at the top level, more inside each of them, and file names she has never typed. She has four years of Python behind her. She knows what a web application does. What she does not know yet is where Rails expects each part of it to live, or what happens between a customer pressing "Book" and the confirmation page appearing.

That is the question for this article: you have opened a Rails project, there are dozens of folders, so what goes where, and how does a request travel through it?

Priya works for Cogwell Cycles, an invented chain of six bicycle repair workshops in Sheffield (cogwellcycles.example). Hannah, the founder, is replacing spreadsheets and a rented booking widget with the business's own web application. Priya and Owen, the second developer, who comes from JavaScript and React, built a two week spike in both Django and Rails, and in how to choose between Django and Rails they chose Rails, by a narrow margin. This is the first chapter of the Rails series, and it builds the same application the Django series will build later, so you can compare like for like.

Everything here is written for Rails 7.1 (the current patch release is 7.1.3, from 16 January 20241) on Ruby 3.3, released on 25 December 20232. The primary source throughout is the official Rails Guides for version 7.1.

The one idea that explains the layout: a name is the wiring

Most frameworks connect their parts with configuration. You write down that this URL goes to that function, that this class uses that table, that this page uses that template. Rails connects most of its parts with names instead. If you call a thing Booking, Rails already knows where its table is, which controller handles it, where its templates live and what its URLs look like.

The Rails Doctrine, the short essay in which David Heinemeier Hansson set out the framework's values in 2016, calls this convention over configuration, and sums it up as "a place for everything and everything in its place"3. His argument is that thousands of small decisions (what to call a primary key, where to put a template) only need to be made once, and if the framework makes them, you get to spend your attention on the parts that are actually yours.

Here is the model I find most useful for a newcomer: a Rails application is a lookup table keyed by a name. The folders are not a filing system you have to memorise. They are the places where Rails looks when it has a name and needs the thing behind it. Once you see the lookups, the layout stops being a maze and the "magic" stops being magic.

Example: one word, eight places

Take the word "booking" in the Cogwell application. Here is every place Rails expects to find it, and the rule that puts it there.

WhatWhere or what Rails expectsThe rule
The model classBooking in app/models/booking.rbClass name in CamelCase, file name in snake_case
The database tablebookingsThe model name, pluralised
The controllerBookingsController in app/controllers/bookings_controller.rbPlural, plus "Controller"
The templatesapp/views/bookings/index.html.erb and friendsFolder named after the controller, file named after the action
The routesresources :bookings in config/routes.rbOne line declares the standard set
The URLs/bookings, /bookings/new, /bookings/42Derived from the resource name
The URL helpersbookings_path, booking_path(booking)Derived from the route names
The model testtest/models/booking_test.rbMirrors the file it tests

Two words show the casing rule better than one. JobCard, the card that moves across the workshop board, lives in app/models/job_card.rb, its table is job_cards, and its controller is JobCardsController. The Active Record guide states the rule plainly: model classes are singular in CamelCase, tables are plural with underscores4. The controller guide adds that controller names are preferably plural, which is what lets the standard route generator find them without extra configuration5.

The consequence for Priya is practical. When she wonders where something is, she does not search. She takes the name, applies the rule, and opens the file.

Where everything lives: the folders, one by one

The Getting Started guide lists the top level folders of a new application and what each one is for6. Here is that list, applied to Cogwell, with the subfolders of app and config opened up, because that is where most of the work happens.

Folder or fileWhat belongs thereIn the Cogwell application
app/modelsClasses that represent business data and rules, usually backed by a tableBooking, JobCard, Part, Invoice
app/controllersClasses that receive a request and decide what to do with itBookingsController, JobCardsController
app/viewsTemplates that turn data into HTML, plus layouts and partialsThe booking form, the workshop board
app/helpersSmall methods used by templates to format thingsShowing a price in pounds, a slot time
app/jobsWork that runs outside the request, in the backgroundThe nightly parts reorder report
app/mailersClasses that build emails, with their templates in app/views"Your bike is ready"
app/channelsAction Cable channels for WebSocket connectionsLive updates, if the board needs them
app/javascriptJavaScript for the browser, with importmap by defaultSmall Stimulus controllers
app/assetsStylesheets, images and the asset manifestThe workshop board's styles
config/routes.rbThe map from URLs to controller actionsresources :bookings
config/environmentsSettings that differ between development, test and productionEmail delivery, logging, caching
config/initializersRuby files that run once when the application bootsParameter filtering, inflections
config/credentials.yml.encEncrypted secrets, such as API keysThe SMS provider's key
db/migrateMigrations: small Ruby files that change the database schema"Create bookings", "add status to job cards"
db/schema.rbThe current shape of the database, generated from the migrationsNever edited by hand
libCode that is not specific to one model or request, and Rake tasksA small VAT calculator, custom tasks
testTests, fixtures and test helperstest/models/booking_test.rb
binScripts: bin/rails, bin/setup, and othersThe commands you run every day
Gemfile and Gemfile.lockThe libraries (gems) the application uses, and their exact versionsRails, Puma, the PostgreSQL adapter
public, log, tmp, storage, vendorStatic files, log files, temporary files, uploaded files on disk, vendored codeError pages, development logs, photos in development

A Rails 7.1 application also comes with a Dockerfile, a .dockerignore and a config.ru6. The Dockerfile is new in 7.1 and gives you a production container image from day one7. The config.ru file is the entry point for the web server, and you will meet it again in the section on the request.

app: the code that answers requests

Everything in app is your application's own code, and every subfolder of app that holds Ruby classes is loaded automatically, a point the section on autoloading explains8. The first four subfolders are the model, view and controller (MVC) pattern plus helpers, which the next section explains. jobs, mailers and channels hold the work that happens outside a normal page request: background tasks, email and WebSocket connections. Chapter 11 of this series covers those three in depth.

You can also add your own folders. If Cogwell's code grows a set of classes that each perform one business operation, Priya can create app/services and Rails picks it up without any configuration8. Whether she should is a judgement call that chapter 14 of this series discusses. For now, the rule is that a new folder under app is free, and that Rails will expect the file names inside it to match the class names.

config: the code that runs once, at boot

config holds the decisions that are made once, when the application starts. config/application.rb holds settings for every environment. config/environments/production.rb overrides them for production, and its siblings do the same for development and test. Files in config/initializers run after the framework and the gems have loaded, sorted by name and loaded one by one9. And config/routes.rb is the one file in this folder you will edit almost daily.

db: the history of the database

db/migrate holds the migrations, each a small Ruby file with a timestamp in its name, recording one change to the database. db/schema.rb is the result: the current shape of every table, regenerated each time a migration runs. Chapter 9 of this series covers Active Record and migrations properly. The one thing to know now is that schema.rb is generated. If you change it by hand, the next migration overwrites your change.

lib, bin, test and the Gemfile

lib is for code that is not part of one feature, and for Rake tasks in lib/tasks. In Rails 7.1, a new application calls config.autoload_lib(ignore: %w(assets tasks)) in config/application.rb, which means Ruby files in lib are now loaded automatically too, while the assets and tasks folders are left alone7. bin holds the commands. test mirrors app: models are tested in test/models, controllers in test/controllers, and full browser tests in test/system. The Gemfile lists the libraries, and Gemfile.lock records the exact version of each one, so that every developer and every server runs the same code.

Example: where Cogwell's features land

Hannah's list of requirements is the best test of the table. Here is each feature, and the folders it will touch.

FeatureWhere the code goes
Online booking with a time slot per mechanicapp/models/booking.rb, app/controllers/bookings_controller.rb, app/views/bookings
The live workshop board (waiting, in repair, ready)app/models/job_card.rb, app/controllers/job_cards_controller.rb, app/views/job_cards, a little JavaScript in app/javascript
Before and after photos on job cardsThe model (Active Storage attachments), config/storage.yml for where files are kept
Parts stock and the nightly reorder reportapp/models/part.rb, a job in app/jobs, a schedule configured outside the request
"Your bike is ready" by email and SMSA mailer in app/mailers, its templates in app/views, the SMS key in credentials
The managers' back officeControllers under app/controllers/admin, views under app/views/admin
Invoices with VATapp/models/invoice.rb, perhaps a calculator class in lib or app/models
ReportingQuery methods on the models, a controller and views for the reports

Nothing on that list needs a folder Rails did not already create, except admin, and that is just a namespace: Admin::BookingsController in app/controllers/admin/bookings_controller.rb.

Model, view, controller, told with a booking

MVC is an old pattern for separating the three jobs every interactive application does: holding the data and the rules (model), showing the data (view), and responding to what the user did (controller). The Action Controller guide describes the controller as the middleman between the other two: it fetches or saves data through the model and uses a view to produce the HTML5.

Example: the model

# app/models/booking.rb
class Booking < ApplicationRecord
  belongs_to :workshop
  belongs_to :mechanic
  belongs_to :customer
  belongs_to :bike
  has_one :job_card

  validates :starts_at, presence: true

  # All bookings that start on the given day
  scope :on_day, ->(day) { where(starts_at: day.all_day) }
end

Notice what is missing. There is no list of columns and no table name. Active Record reads the columns from the bookings table the first time it needs them, and the table name comes from the class name4. The model holds the rules: a booking belongs to a workshop, a mechanic, a customer and a bike, it must have a start time, and you can ask for the bookings on any day.

Example: the controller

# app/controllers/bookings_controller.rb
class BookingsController < ApplicationController
  before_action :set_booking, only: :show

  # GET /bookings: today's bookings, earliest first
  def index
    @bookings = Booking.on_day(Date.current)
                       .includes(:customer, :mechanic)
                       .order(:starts_at)
  end

  # GET /bookings/42
  def show
  end

  # GET /bookings/new
  def new
    @booking = Booking.new
  end

  # POST /bookings
  def create
    @booking = Booking.new(booking_params)

    if @booking.save
      redirect_to @booking, notice: "Booked. See you on the day."
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def set_booking
    @booking = Booking.find(params[:id])
  end

  # Strong parameters: only these fields may come from the form
  def booking_params
    params.require(:booking)
          .permit(:workshop_id, :mechanic_id, :customer_id, :bike_id, :starts_at)
  end
end

Each public method is an action, and each action matches one route. The variables that start with @ are instance variables, and they are how the controller hands data to the view. show is empty, and it still works: set_booking has already loaded the booking, and Rails renders the matching template by itself. That is the implicit rendering the next sections explain. booking_params uses strong parameters, which forbid any form field you have not listed from reaching the model5.

Example: the view and the layout

<%# app/views/bookings/index.html.erb %>
<h1>Today's bookings</h1>

<ul>
  <% @bookings.each do |booking| %>
    <li>
      <%= l booking.starts_at, format: :short %>:
      <%= booking.customer.name %> with <%= booking.mechanic.name %>
      <%= link_to "Open", booking %>
    </li>
  <% end %>
</ul>

ERB (Embedded Ruby) is HTML with Ruby inside: <% %> runs Ruby, <%= %> runs it and prints the result. link_to "Open", booking asks the router for the booking's URL, so the template never contains /bookings/42 as text.

The template does not include the page's <head>, the stylesheet or the navigation. Those live in the layout, and the template is placed where the layout says yield:

<%# app/views/layouts/application.html.erb, shortened %>
<!DOCTYPE html>
<html>
  <head>
    <title>Cogwell Cycles</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

Rails looks for a layout named after the controller first (app/views/layouts/bookings.html.erb) and falls back to application.html.erb when there is none10.

A word for Python developers: the false friends

Priya's Python background helps more than it hinders, with one trap. Django uses the same three ideas under different names. The Django documentation explains that what it calls a "view" is the function that decides which data is shown, and what it calls a "template" decides how it looks, so Django describes itself as model, template, view11.

The jobRails calls itDjango calls it
Data and business rulesModel (Active Record)Model
Handle a request, pick the dataController actionView
Turn data into HTMLView (template)Template
Map URLs to codeconfig/routes.rburls.py (the URLconf)
Settingsconfig/application.rb and config/environmentssettings.py
Wrap every requestRack middlewareMiddleware

So when Owen says "the view" and Priya hears "the function that handles the request", they are talking about two different files. Agreeing on the Rails names on day one saves a week of small misunderstandings.

How a request travels through a Rails application

Now the second half of the reader's question. A customer on their phone opens the page that lists today's bookings at a workshop (a manager's page, in practice, but it keeps the example short). Here is everything that happens between the request leaving the phone and the HTML arriving back.

Tap or click to enlarge

Step 1: Puma, the web server

A Rails application does not listen on the network by itself. A web server does that, and the default is Puma, which bin/rails server starts for you6. Puma accepts the connection, reads the request and serves it in a thread from a pool. In production it can also run several worker processes, each with its own thread pool, which Puma calls clustered mode12. A new Rails 7.1 application configures Puma in config/puma.rb with five threads by default, matching the default size of Active Record's database connection pool13.

Step 2: Rack, the contract between server and framework

Puma knows nothing about Rails. It knows Rack. Rack is a tiny agreement for Ruby web software: an application is any object with a call method that takes one argument, a hash describing the request (the "environment"), and returns three things: a status, the headers and the body14. Python developers will recognise the idea. The Rack specification says itself that its environment variables were adopted from Python Enhancement Proposal (PEP) 333, the standard that defines the Web Server Gateway Interface (WSGI)14, one of the two interfaces Django can sit on.

config.ru is where the two meet. Its key line is run Rails.application, and the Rails on Rack guide confirms that Rails.application is the Rack application object any Rack server should use15.

Step 3: the middleware stack

Before your code sees the request, it passes through a stack of middleware. Each middleware is a Rack application that wraps the next one: it can look at the request on the way in, change it, answer it by itself, or let it through and then look at the response on the way out. You can print the stack:

$ bin/rails middleware
use ActionDispatch::HostAuthorization
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActionDispatch::ServerTiming
...
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ContentSecurityPolicy::Middleware
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Rack::TempfileReaper
run Cogwell::Application.routes

The Rails on Rack guide explains each one15. A few worth knowing on day one: HostAuthorization rejects requests for host names the application does not expect, Static serves files from public, Cookies, Session::CookieStore and Flash give your controller the cookies, the session and the one time messages such as "Booked. See you on the day.", and ActiveRecord::Migration::CheckPending (in development) stops you with a clear error when you forgot to run a migration. The last line is the important one: at the bottom of the stack sits the router.

Step 4: the router

The router reads config/routes.rb from top to bottom and dispatches the request to the first route that matches16. Here is Cogwell's:

# config/routes.rb
Rails.application.routes.draw do
  # Health check for load balancers, generated by Rails 7.1
  get "up" => "rails/health#show", as: :rails_health_check

  resources :bookings, only: [:index, :show, :new, :create]

  root "bookings#new"
end

resources :bookings is a resource route. On its own it declares seven routes, one for each standard action (index, show, new, create, edit, update, destroy), each tied to an HTTP verb and a URL, and the routing guide calls this the Rails default16. only: keeps the four Cogwell needs now. The up route is new in Rails 7.1: a new application ships with it so that a load balancer can check whether the application has booted17.

Step 5: the controller and its before actions

Rails creates a new instance of BookingsController for this one request and calls the action. Before it does, it runs the before actions. These are methods registered with before_action, and the Action Controller guide notes the one property that matters most: if a before action renders or redirects, the action does not run5. That is how a login check works. Chapter 13 of this series uses exactly that to keep the back office for managers.

Step 6: Active Record talks to the database

The index action builds a query: bookings that start today, with their customers and mechanics, earliest first. Active Record turns that into SQL when the data is first needed, which in this case is when the template loops over @bookings. The includes(:customer, :mechanic) part tells Active Record to load the customers and mechanics in two extra queries, instead of one query per booking. Chapter 9 explains why that matters.

Step 7: the view and the layout are rendered

The action ends without calling render. The Layouts and Rendering guide describes what happens next as convention over configuration in action: if you do not render explicitly, Rails looks for a template named after the action in the controller's view folder, here app/views/bookings/index.html.erb, and renders it inside the layout10.

Step 8: the response goes back out

The rendered HTML becomes the body of the response. On the way back, the middleware gets its turn again: Rack::ETag adds a fingerprint of the body so the browser can cache it, Rack::ConditionalGet sends an empty "not modified" answer if the browser already has that exact page15. Puma writes the response to the network, and the thread goes back to the pool for the next customer.

Example: one request in the development log

Every step above leaves a trace in log/development.log. Here is what Priya sees when she opens the bookings page on her laptop. The timings are invented for this example, the format is what Rails 7.1 writes:

Started GET "/bookings" for 127.0.0.1 at 2024-01-27 09:14:03 +0000
Processing by BookingsController#index as HTML
  Booking Load (4.1ms)  SELECT "bookings".* FROM "bookings" WHERE "bookings"."starts_at" BETWEEN $1 AND $2 ORDER BY "bookings"."starts_at" ASC
  Customer Load (2.3ms)  SELECT "customers".* FROM "customers" WHERE "customers"."id" IN ($1, $2, $3)
  Mechanic Load (1.6ms)  SELECT "mechanics".* FROM "mechanics" WHERE "mechanics"."id" IN ($1, $2)
  Rendered bookings/index.html.erb within layouts/application (Duration: 18.7ms | Allocations: 9120)
  Rendered layout layouts/application.html.erb (Duration: 21.4ms | Allocations: 11870)
Completed 200 OK in 48ms (Views: 21.4ms | ActiveRecord: 9.8ms | Allocations: 18240)

Read it line by line and you can retrace the whole journey:

  • Started GET "/bookings" is the request arriving through Puma and the middleware.
  • Processing by BookingsController#index is the router's decision.
  • The three Load lines are Active Record's queries. Three queries, not one per booking, thanks to includes.
  • The two Rendered lines are the template and then the layout around it.
  • Completed 200 OK in 48ms is the total, split into time in views and time in Active Record. The rest, here 16.8 milliseconds, is everything else: middleware, routing, your controller's Ruby code and, in development, the reloading of changed files.
An invented development log entry for Cogwell's bookings page took 48 milliseconds in total. Views took 21.4 milliseconds, Active Record 9.8 milliseconds, and everything else, middleware, routing and controller code, 16.8 milliseconds. Tap or click to enlarge

The point of the chart is the shape, not the numbers. The two parts that grow with the business, views and queries, are the two parts that live in your app folder. The framework's share stays roughly constant.

How much traffic one Rails process can carry

Hannah's first worry, when Priya explains threads and processes, is Saturday morning: 30% of the week's online bookings arrive between Friday 6pm and Saturday noon. Will one server cope? A formula from queueing theory, Little's law, answers that in three lines18. Foundations: ratios and rates

L=λWL = \lambda W

where LL is the average number of requests being worked on at the same moment, λ\lambda is the arrival rate in requests per second, and WW is the average time one request takes, in seconds. John Little proved in 1961 that this holds for a queue in a steady state under very general conditions, whatever the pattern of arrivals18.

Example: Cogwell's Saturday rush

The facts: about 1,150 bookings a week, 30% of them in the 18 hours from Friday 6pm to Saturday noon, which is 345 bookings, or about 19 an hour. Two assumptions, labelled as mine: the busiest hour runs at three times that average, so 58 bookings, and each online booking takes 12 requests (choosing a workshop, a mechanic, a slot, entering details, confirming). On top come the 38 mechanics, and I assume each makes one request a minute while moving job cards on the board. Foundations: ratios and rates

λ=58×123600+3860≈0.19+0.63=0.82\lambda = \frac{58 \times 12}{3600} + \frac{38}{60} \approx 0.19 + 0.63 = 0.82

with λ\lambda in requests per second, 58×1258 \times 12 the customer requests in the busiest hour, 36003600 the seconds in an hour, and 38/6038 / 60 the mechanics' one request a minute each, turned into requests per second.

If a request takes 100 milliseconds on average, W=0.1W = 0.1, and the same formula gives the answer (Foundations: ratios and rates):

L=0.82×0.1≈0.08L = 0.82 \times 0.1 \approx 0.08

where L≈0.08L \approx 0.08 means that, on average, the application is busy with less than one tenth of one request at a time.

One Puma process with the default five threads can work on five requests at once. Cogwell's busiest hour needs a small fraction of one. Even if every assumption is off by a factor of ten, a single modest server has room to spare.

The lesson is not "Rails is fast" or "Rails is slow". It is that, for a business of Cogwell's size, the number that matters is WW, the time one request takes, and WW is decided by the queries and templates in app, not by the server. Chapter 4 of the comparison series, on performance, hosting and hiring, puts both frameworks through the same arithmetic.

The magic, and the command that prints each piece

Newcomers often describe Rails as magic, and they mean it as a warning. My rule is simple: never accept magic you cannot print. Every convention in Rails is a lookup, and for every lookup there is a command or a one line question that shows you the answer. Once you know them, nothing in the framework is hidden.

The "magic"What it really isHow to print it
The model knows its tableThe class name, pluralisedbin/rails runner 'p Booking.table_name'
A URL reaches the right actionRoutes read top to bottombin/rails routes -c bookings
Classes are available without requireZeitwerk maps file names to class namesbin/rails zeitwerk:check
Requests get cookies, sessions, flashThe middleware stackbin/rails middleware
The action renders a page by itselfTemplate lookup by controller and action nameThe Rendered lines in the log

Naming and the table

Booking.table_name returns "bookings". If a table ever has to break the rule (a legacy database, say), you set self.table_name in the model, and the Active Record guide shows how4. You will rarely need to, and when you do, the exception is written in the one place a reader would look.

Routes

$ bin/rails routes -c bookings
     Prefix Verb URI Pattern             Controller#Action
   bookings GET  /bookings(.:format)     bookings#index
            POST /bookings(.:format)     bookings#create
new_booking GET  /bookings/new(.:format) bookings#new
    booking GET  /bookings/:id(.:format) bookings#show
       root GET  /                       bookings#new

The Prefix column is the name of the URL helper: bookings gives you bookings_path, new_booking gives you new_booking_path. The routing guide documents the command and its filters, -c for a controller and -g to search16.

How autoloading works with Zeitwerk

In plain Ruby you load a file with require before you use what is in it. In a Rails application you never do that for your own code. Rails sets up Zeitwerk, a code loader written by Xavier Noria, and Zeitwerk works on one rule: file paths match constant paths, with folders acting as namespaces19. app/models/job_card.rb must define JobCard. app/controllers/admin/bookings_controller.rb must define Admin::BookingsController8.

The autoloading guide adds the two details that matter in practice8. First, every subfolder of app is an autoload path, except assets, javascript and views. Second, in development Rails reloads changed files between requests, which is why you can edit a controller and refresh the browser without restarting anything. In production, the application loads everything once at boot instead, which is called eager loading.

Example: the file name that broke the board

Owen adds a class for the workshop board and saves it as app/models/jobcard.rb, with class JobCard inside. In development, the board page fails with an "uninitialized constant" error, which is confusing, because the class is clearly there. Priya runs the check:

$ bin/rails zeitwerk:check
Hold on, I am eager loading the application.
expected file app/models/jobcard.rb to define constant Jobcard, but didn't

Zeitwerk read the file name jobcard, expected a constant Jobcard, and found JobCard instead. Renaming the file to job_card.rb fixes it, and the check now prints "All is good!". The message is exact, which is the point: the convention is strict, and the tool that enforces it tells you precisely what it expected. Running bin/rails zeitwerk:check in continuous integration (CI) catches this before it reaches production, where eager loading would make the application fail at boot.

Middleware and rendering

bin/rails middleware prints the stack you saw earlier. And the template lookup shows up in the log on every request, in the Rendered lines. If a page renders the wrong template, those lines tell you which file Rails used and which layout wrapped it.

Environments and credentials: one codebase, three behaviours

The same code runs on Priya's laptop, in the test suite and on the production server, and it should not behave identically in all three. In development you want detailed errors and instant reloading. In tests you want speed and no real emails. In production you want caching, secure cookies and quiet logs. Rails ships with three environments for this, development, test and production, and lets you add more, such as staging9.

Each environment has a file in config/environments. A few lines from a new Rails 7.1 application show the difference:

# config/environments/development.rb (excerpt)
config.enable_reloading = true   # pick up code changes between requests
config.eager_load = false        # load classes only when first used

# config/environments/production.rb (excerpt)
config.enable_reloading = false  # code never changes while running
config.eager_load = true         # load everything at boot
config.force_ssl = true          # HTTPS only, secure cookies

The environment is chosen by the RAILS_ENV variable, and it defaults to development.

Credentials: secrets in the repository, safely

An application needs secrets: the key that signs cookies, the SMS provider's API key, the email service's token. Rails keeps them in config/credentials.yml.enc, an encrypted file that can be committed to version control because it is unreadable without the key. The key lives in config/master.key, which is never committed, or in the RAILS_MASTER_KEY environment variable on the server20. Rails can also keep a separate credentials file per environment, which takes precedence over the shared one in that environment21.

Example: Cogwell's SMS key

Priya adds the SMS provider's key for production only:

$ bin/rails credentials:edit --environment production

This opens a decrypted copy in her editor and creates config/credentials/production.yml.enc and its key config/credentials/production.key if they do not exist yet21. She adds:

sms:
  api_key: the_real_key_from_the_provider

When she saves, the file is encrypted again and the plain copy is deleted. In the code that sends "your bike is ready", she reads it like this:

Rails.application.credentials.dig(:sms, :api_key)

The production key goes into the server's environment, never into the repository. One more line belongs here, because the SMS goes to a customer's phone number. Rails filters sensitive form fields out of the log using a list in config/initializers/filter_parameter_logging.rb, which by default covers passwords, tokens, keys and similar22. Priya adds :phone to that list, so customers' phone numbers never land in the log files. It is a small habit with a data protection payoff.

Where does this code belong? A decision path

The folder table tells you what each folder holds. In practice you face the reverse question: you have a piece of code, so where does it go? Here is the second model I give newcomers. Sort code by when it runs.

  • Code that runs once, at boot, belongs in config: settings in config/application.rb or an environment file, setup in an initializer.
  • Code that runs when the database changes shape belongs in db/migrate.
  • Code that runs on every request belongs in app, in the folder for its job: model, controller, view, helper.
  • Code that runs outside a request, later or on a schedule, belongs in app/jobs (and its trigger outside the request).
  • Code that runs when a person types a command belongs in a Rake task in lib/tasks or a script in bin.

That sorting gets you to the right folder almost every time. Inside app, one more question decides the subfolder: is it a business rule, request handling, or presentation?

Tap or click to enlarge

The diagram's recommended path ends in app/models on purpose. When in doubt, a business rule belongs in a model, not in a controller or a template. A rule in a model is written once and used everywhere: by the booking form, the back office, the API for the mechanics' app and the tests. A rule in a controller is used by that one page and copied, slightly differently, into the next.

Example: five pieces of Cogwell code, sorted

"A booking cannot overlap another booking for the same mechanic." That is a business rule, true for every way a booking is created. It belongs in app/models/booking.rb, as a validation.

"Show slot times as 9am, 2.30pm." Presentation, used in several templates. A helper method in app/helpers/bookings_helper.rb.

"Every night at 2am, list the parts below their reorder level and email the list." Runs outside a request, on a schedule. A job in app/jobs/parts_reorder_report_job.rb, which builds the list from a method on the Part model and hands it to a mailer.

"Only managers may open the back office." It decides what happens with a request: a before_action in Admin::BaseController, from which every back office controller inherits.

"Add a status column to job cards." Changes the database structure: a migration in db/migrate, after which db/schema.rb updates itself.

Five decisions, none of which needed a meeting. That is what the conventions buy a small team.

How the Rails conventions compare with Django's explicit wiring

It would be unfair to present all of this as simply better. Django makes the opposite choice on purpose. Its design philosophies page states that explicit is better than implicit, and that the framework should avoid too much magic unless it buys a large convenience that cannot be had another way23. In a Django project, the URL patterns in urls.py name the view function for each path, and Django runs through them in order until one matches24. Middleware is listed by name in the settings, in the order it runs25.

Both approaches pay for what they get:

  • Rails buys brevity and uniformity. One line, resources :bookings, declares seven routes, and every Rails application is laid out the same way, so a developer who knows one can find their way around another on the first day. The cost is that the wiring is invisible until you learn the lookups. A newcomer reading BookingsController cannot see from the file which URL leads to it.
  • Django buys readability from the file you are in. Open urls.py and every connection is written down. The cost is more lines to write and keep in sync, and more room for two projects to be organised differently.

My view: for a small team that stays on one application for years, as Cogwell will, the Rails trade is a good one, because the price of learning the lookups is paid once and the uniformity pays back every day. For a team that moves between many small projects, or that prefers to read connections rather than know them, Django's explicitness is a fair and reasonable preference. The comparison series opens with exactly this split in two answers to the same question, and the Django series will show the Django version of the spike, folder by folder, in its own first chapter.

There is also a middle position, and it is the one I hold: conventions are only acceptable if they can be printed. That is why the command table above matters more than any amount of reassurance that "Rails just knows".

For the person paying for this

Hannah does not need to read Ruby to check that her application is in good shape. A handful of questions, asked at a review, tell her most of what she needs to know.

AskA good answer
Does the project follow the standard Rails layout?Yes, and any extra folder under app has a one line reason in the README
Where do the business rules live, such as overlapping bookings?In the models, with tests in test/models
Is the master key in the repository?No. It is in a password manager and in the server's environment
Does bin/rails zeitwerk:check run in CI?Yes, so a misnamed file cannot reach production
Are customers' phone numbers and emails filtered from the logs?Yes, in filter_parameter_logging.rb
How long does the slowest page take, and why?A number from the logs, with the split between queries and views
Which Rails and Ruby versions does the application run on, and until when are they supported?Rails 7.1 on Ruby 3.3, with the support dates written down

The questions about versions and support connect directly to five years with Django or Rails, which works out what upgrades cost over the life of an application.

For what it is worth, this is how I work too. I build web applications on Ruby on Rails, test first, and the standard layout is the first thing I keep intact, because it is what lets the next developer, or the client's own team, pick the code up without me. The client owns the code, the accounts and the data, and a conventional structure is a large part of what makes that ownership real. If you are planning an application like Cogwell's, my web application development page explains how I build them, and my prices are published in full.

Conclusion

A Rails application looks like dozens of folders, but it behaves like one lookup table keyed by a name. Call a thing Booking, and Rails knows its file, its table, its controller, its templates, its URLs and its tests. The folders are where those lookups land: app for the code that answers requests, config for what runs once at boot, db for the history of the database, lib, bin and test around them.

A request travels a fixed path: Puma accepts it, Rack hands it down the middleware stack, the router picks an action, before actions may stop it, the action asks Active Record for data, the view renders inside the layout, and the response goes back out the same way. The development log shows every step, and for a business of Cogwell's size the time that matters is spent in your own queries and templates, not in the framework.

Two rules carry most of the weight. Sort code by when it runs, and you will put it in the right folder. And never accept magic you cannot print: bin/rails routes, bin/rails middleware, bin/rails zeitwerk:check and the log turn every convention into something you can see. The next chapter starts the Cogwell application from rails new, and covers the first decisions that are hard to change later.

Planning a web application and want to see how it would be laid out before a line is written? Book the free workshop: we map your features to a Rails structure together, and the first two weeks of work are on me.

Sources

  1. 1.

    Rafael França, Rails 7.1.3 has been released, rubyonrails.org, 16 January 2024, https://rubyonrails.org/2024/1/16/Rails-7-1-3-has-been-released

  2. 2.

    Ruby core team, Ruby 3.3.0 Released, ruby-lang.org, 25 December 2023, https://www.ruby-lang.org/en/news/2023/12/25/ruby-3-3-0-released/

  3. 3.

    David Heinemeier Hansson, The Rails Doctrine, rubyonrails.org, 2016, https://rubyonrails.org/doctrine

  4. 4.

    Ruby on Rails Guides (Rails 7.1), Active Record Basics, sections 2.1 Naming Conventions and 3 Overriding the Naming Conventions, https://guides.rubyonrails.org/v7.1/active_record_basics.html

  5. 5.

    Ruby on Rails Guides (Rails 7.1), Action Controller Overview, sections 1 to 4 and 8 Filters, https://guides.rubyonrails.org/v7.1/action_controller_overview.html

  6. 6.

    Ruby on Rails Guides (Rails 7.1), Getting Started with Rails, section 3.2 Creating the Blog Application and 4.1 Starting Up the Web Server, https://guides.rubyonrails.org/v7.1/getting_started.html

  7. 7.

    Ruby on Rails Guides, Ruby on Rails 7.1 Release Notes, sections 2.1 Generate Dockerfiles for new Rails applications and 2.8 Introducing config.autoload_lib, October 2023, https://guides.rubyonrails.org/v7.1/7_1_release_notes.html

  8. 8.

    Ruby on Rails Guides (Rails 7.1), Autoloading and Reloading Constants, sections 2 Project Structure, 3 config.autoload_paths and 14 Testing, https://guides.rubyonrails.org/v7.1/autoloading_and_reloading_constants.html

  9. 9.

    Ruby on Rails Guides (Rails 7.1), Configuring Rails Applications, sections 3.21 Creating Rails Environments and 5 Using Initializer Files, https://guides.rubyonrails.org/v7.1/configuring.html

  10. 10.

    Ruby on Rails Guides (Rails 7.1), Layouts and Rendering in Rails, sections 2.1 Rendering by Default and 2.2.14 Finding Layouts, https://guides.rubyonrails.org/v7.1/layouts_and_rendering.html

  11. 11.

    Django Software Foundation, FAQ: General, "Django appears to be a MVC framework...", Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/faq/general/

  12. 12.

    Puma contributors, Puma README, sections Thread Pool and Clustered mode, version 6.4.2, January 2024, https://github.com/puma/puma/blob/v6.4.2/README.md

  13. 13.
  14. 14.

    Rack contributors, Rack SPEC, version 3.0.8, June 2023, https://github.com/rack/rack/blob/v3.0.8/SPEC.rdoc

  15. 15.

    Ruby on Rails Guides (Rails 7.1), Rails on Rack, sections 2.1 Rails Application's Rack Object, 3.1 Inspecting Middleware Stack and 3.3 Internal Middleware Stack, https://guides.rubyonrails.org/v7.1/rails_on_rack.html

  16. 16.

    Ruby on Rails Guides (Rails 7.1), Rails Routing from the Outside In, sections 1, 2 and 6.1 Listing Existing Routes, https://guides.rubyonrails.org/v7.1/routing.html

  17. 17.

    Ruby on Rails, application template config/routes.rb, Rails 7.1.3 source, https://github.com/rails/rails/blob/v7.1.3/railties/lib/rails/generators/rails/app/templates/config/routes.rb.tt

  18. 18.

    John D. C. Little, A Proof for the Queuing Formula: L = λW, Operations Research 9 (3), 383 to 387, INFORMS, 1961, https://doi.org/10.1287/opre.9.3.383

  19. 19.

    Xavier Noria, Zeitwerk README, section The idea: File paths match constant paths, version 2.6.12, September 2023, https://github.com/fxn/zeitwerk/blob/v2.6.12/README.md

  20. 20.

    Ruby on Rails Guides (Rails 7.1), Securing Rails Applications, section 10.1 Custom Credentials, https://guides.rubyonrails.org/v7.1/security.html

  21. 21.

    Ruby on Rails, rails credentials command help (USAGE), Rails 7.1.3 source, https://github.com/rails/rails/blob/v7.1.3/railties/lib/rails/commands/credentials/USAGE

  22. 22.

    Ruby on Rails, application template config/initializers/filter_parameter_logging.rb, Rails 7.1.3 source, https://github.com/rails/rails/blob/v7.1.3/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb.tt

  23. 23.

    Django Software Foundation, Design philosophies, section Overall: Explicit is better than implicit, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/misc/design-philosophies/

  24. 24.

    Django Software Foundation, URL dispatcher, section How Django processes a request, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/http/urls/

  25. 25.

    Django Software Foundation, Middleware, section Middleware order and layering, Django 5.0 documentation, https://docs.djangoproject.com/en/5.0/topics/http/middleware/

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter