Rails: Convention over Configuration

Rails: Convention over Configuration in Ruby: --- Every room in a chain hotel follows the same fit-out.


The Analogy: The Chain Hotel Standardised Room Fit-Out

Every room in a chain hotel follows the same fit-out. The electrician knows the light switch sits 1200 millimetres from the door on the hinge side. The plumber knows the waste pipe runs under the basin against the north wall. The housekeeper knows the safe is on the second shelf of the wardrobe, and the extra pillows go on the top shelf. Nobody consults a room-specific drawing -- the brand manual is the drawing, and every standard room in the chain follows it.

A fitter walks into room 307 and sees a blank shell. They do not radio the design office. They open the brand manual, which says: basin on the north wall, power outlets at 300-millimetre intervals along the skirting board, wardrobe on the west wall, desk facing the window, television bracket at exactly 1400 millimetres on the axis of the bed. The room number tells them nothing about the layout. The brand tells them everything. The only document that room 307 needs is a deviation sheet, and for a standard room the deviation sheet is blank.

Deviation sheets exist for corner suites, accessible rooms, and the penthouse. Only the differences are drawn: the roll-in shower that replaces the bath, the desk moved to clear the turning circle, the kitchenette added to the penthouse. Everything not on the deviation sheet is understood to follow the brand manual. This is why a chain can fit out forty rooms a week while a boutique hotel needs a bespoke drawing for each one.

The convention fails in four ways. A fitter who ignores the manual and hangs the television where they think it looks best creates a room that passes its own inspection but breaks the fire-escape plan printed on the back of the door, because that plan shows the furniture where the manual says it goes. A maintenance engineer walking in at 2 AM finds the isolation switch in the wrong place. The housekeeper's cart is stocked for shelves that do not match. And the guest who booked on the strength of the website photos finds a room that is not quite the one in the photos. Convention is not a constraint on the designer -- it is a contract with every person who enters the room after the designer has left.


Syntax or Core Structure

Rails is a brand manual for web applications. You give it one name -- Reservation -- and it derives the table, the file, the controller, the routes, the foreign keys, and the test path from that single word. The two rules that drive almost everything are: CamelCase becomes snake_case, and a model name is singular while its table is plural.

# convention.rb -- how one name decides everything.

def snake(camel)
  camel.gsub(/([a-z])([A-Z])/) { "#{$1}_#{$2}" }.downcase
end

def report(model)
  sn = snake(model)
  pl = sn + "s"
  puts model
  puts "  table        #{pl}"
  puts "  model_file   app/models/#{sn}.rb"
  puts "  ctrl_class   #{model}sController"
  puts "  ctrl_file    app/controllers/#{pl}_controller.rb"
  puts "  view_dir     app/views/#{pl}"
  puts "  foreign_key  #{sn}_id"
end

["Reservation", "RoomType", "GuestPreference"].each { |m| report(m) }

ACTIONS = [
  ["GET",    "/%s",          "index"],
  ["GET",    "/%s/new",      "new"],
  ["POST",   "/%s",          "create"],
  ["GET",    "/%s/:id",      "show"],
  ["GET",    "/%s/:id/edit", "edit"],
  ["PATCH",  "/%s/:id",      "update"],
  ["DELETE", "/%s/:id",      "destroy"],
]

puts ""
resource = "reservations"
puts "resources :#{resource}"
ACTIONS.each do |verb, pattern, action|
  path = format(pattern, resource)
  puts format("  %-7s %-24s ReservationsController#%s", verb, path, action)
end

puts ""
puts "belongs_to :room_type -> #{snake('RoomType')}_id"
puts "has_many :reservations -> reservations.#{snake('RoomType')}_id"

Output:

Reservation
  table        reservations
  model_file   app/models/reservation.rb
  ctrl_class   ReservationsController
  ctrl_file    app/controllers/reservations_controller.rb
  view_dir     app/views/reservations
  foreign_key  reservation_id
RoomType
  table        room_types
  model_file   app/models/room_type.rb
  ctrl_class   RoomTypesController
  ctrl_file    app/controllers/room_types_controller.rb
  view_dir     app/views/room_types
  foreign_key  room_type_id
GuestPreference
  table        guest_preferences
  model_file   app/models/guest_preference.rb
  ctrl_class   GuestPreferencesController
  ctrl_file    app/controllers/guest_preferences_controller.rb
  view_dir     app/views/guest_preferences
  foreign_key  guest_preference_id

resources :reservations
  GET     /reservations            ReservationsController#index
  GET     /reservations/new        ReservationsController#new
  POST    /reservations            ReservationsController#create
  GET     /reservations/:id        ReservationsController#show
  GET     /reservations/:id/edit   ReservationsController#edit
  PATCH   /reservations/:id        ReservationsController#update
  DELETE  /reservations/:id        ReservationsController#destroy

belongs_to :room_type -> room_type_id
has_many :reservations -> reservations.room_type_id

Thirty-one lines of output from a handful of lines of convention logic. The only fact supplied was the model name -- "Reservation", "RoomType", "GuestPreference". Every file path, class name, table name and foreign key was derived from that single string by two rules: CamelCase becomes snake_case, and the plural form adds an "s".

The seven REST routes follow the same principle. The single line resources :reservations in a real Rails routes file generates all seven, mapping each verb-and-path pair to a controller action by convention. The developer writes neither the paths nor the wiring; both are derived from the resource name. Note that the format string uses %-24s to left-pad the path column, which is why the controller names line up regardless of how long each path is.

The last two lines show how conventions compose across models. A Reservation that belongs_to :room_type is expected to carry a column called room_type_id in the reservations table. A RoomType that has_many :reservations carries no foreign key at all -- it simply expects that column to exist in the other table. One naming convention binds two tables with no configuration written on either side.


Technical Depth: The Conventions, And What They Cost

Convention over configuration is a trade. You give up the freedom to name things however you like, and in return you never write the wiring that connects them. The trade is only worth it if you know exactly which conventions are in force, because a convention you do not know about is a decision being made for you in silence.

The Core Naming Conventions

Singular model classIts database tableIts foreign key elsewhereIts file location
Reservationreservationsreservation_idapp/models/reservation.rb
RoomTyperoom_typesroom_type_idapp/models/room_type.rb
GuestPreferenceguest_preferencesguest_preference_idapp/models/guest_preference.rb
Invoiceinvoicesinvoice_idapp/models/invoice.rb
BillingAddressbilling_addressesbilling_address_idapp/models/billing_address.rb

Read that table as one rule applied five times. The class is CamelCase and singular. The table is snake_case and plural. The foreign key is the singular snake_case name with _id appended. The file path is the singular snake_case name under app/models. Nothing in any row was configured; every cell after the first was computed from the first by the same two transformations.

Pluralisation Is A Real Dictionary, Not Just Appending s

RULES = [
  [/y$/,  "ies"],
  [/s$/,  "ses"],
  [/x$/,  "xes"],
]

def pluralise(word)
  RULES.each do |pattern, ending|
    return word.sub(pattern, ending) if word =~ pattern
  end
  word + "s"
end

["reservation", "room_type", "address", "box", "policy", "guest"].each do |w|
  puts format("%-12s -> %s", w, pluralise(w))
end

Output:

reservation  -> reservations
room_type    -> room_types
address      -> addresses
box          -> boxes
policy       -> policies
guest        -> guests

Rails ships a full inflector with hundreds of rules, including irregular plurals (person becomes people, mouse becomes mice) and words that do not change (sheep, fish). The five lines above are a toy version, but they show the mechanism: pluralisation is a lookup against ordered rules, not string concatenation. This matters the day you name a model Policy and Rails looks for a policies table -- if your migration created policys, the two never meet, and the error message is about a missing table rather than a naming disagreement.

One Environment File, Many Environments

DEFAULTS = { pool: 5, timeout: 5000, log_level: "debug" }

ENVIRONMENTS = {
  "development" => {},
  "test"       => { log_level: "warn" },
  "production"  => { pool: 25, timeout: 3000, log_level: "info" },
}

def config_for(env)
  DEFAULTS.merge(ENVIRONMENTS.fetch(env))
end

["development", "test", "production"].each do |env|
  c = config_for(env)
  puts format("%-12s pool=%-2d timeout=%-4d log=%s",
              env, c[:pool], c[:timeout], c[:log_level])
end

Output:

development  pool=5  timeout=5000 log=debug
test         pool=5  timeout=5000 log=warn
production   pool=25 timeout=3000 log=info

This is the deviation-sheet idea in code. DEFAULTS is the brand manual. Each environment declares only its differences, and merge fills the rest from the defaults. Development changes nothing, so its row is the pure default. Test overrides one key. Production overrides three. You never restate a value that has not changed, which means the day you raise the default timeout, every environment that did not override it moves together -- and the one that did override it stays put, on purpose. The failure mode hides here too: an environment that overrides a key it did not mean to has quietly opted out of every future change to that default.


Real World Example: A Request Router Built On Convention Alone

A web request arrives as a verb and a path: GET /reservations/42. Nothing in that request names a Ruby class or a method. The router's whole job is to turn the request into a controller class and an action method by convention, dispatch to it, and let the controller find its model -- again by convention. The program below is a miniature of exactly that pipeline, small enough to hand-trace and honest about where the convention stops holding.

# router.rb -- verb + path in, controller#action out, by convention only.

class Controller
  def initialize(resource)
    @resource = resource
  end

  def index
    "listing all #{@resource}"
  end

  def show(id)
    "showing #{@resource} #{id}"
  end

  def create
    "creating a #{@resource}"
  end

  def destroy(id)
    "destroying #{@resource} #{id}"
  end
end

# Convention: verb + shape of path decides the action name.
def action_for(verb, has_id)
  case [verb, has_id]
  when ["GET", false]    then "index"
  when ["GET", true]     then "show"
  when ["POST", false]   then "create"
  when ["DELETE", true]  then "destroy"
  else nil
  end
end

def route(verb, path)
  parts = path.split("/").reject(&:empty?)
  resource = parts[0]
  id = parts[1]
  has_id = !id.nil?

  return format("404 no route for %s %s", verb, path) if resource.nil?

  action = action_for(verb, has_id)
  return format("405 %s not allowed on /%s", verb, resource) if action.nil?

  ctrl = Controller.new(resource)
  result = has_id ? ctrl.send(action, id) : ctrl.send(action)
  format("200 %-7s /%-18s -> %s", verb, path.sub(%r{^/}, ""), result)
end

REQUESTS = [
  ["GET",    "/reservations"],
  ["GET",    "/reservations/42"],
  ["POST",   "/reservations"],
  ["DELETE", "/reservations/42"],
  ["GET",    "/room_types"],
  ["GET",    "/room_types/7"],
  ["PATCH",  "/reservations/42"],
  ["DELETE", "/reservations"],
]

puts "requests: #{REQUESTS.size}"

results = REQUESTS.map { |verb, path| route(verb, path) }
results.each { |line| puts line }

ok = results.count { |r| r.start_with?("200") }
bad = results.size - ok
puts format("handled %d, refused %d, total %d", ok, bad, results.size)
puts "reconciled: #{ok + bad == REQUESTS.size}"

by_code = results.group_by { |r| r[0, 3] }
by_code.keys.sort.each do |code|
  puts format("  %s x%d", code, by_code[code].size)
end

Output:

requests: 8
200 GET     /reservations       -> listing all reservations
200 GET     /reservations/42    -> showing reservations 42
200 POST    /reservations       -> creating a reservations
200 DELETE  /reservations/42    -> destroying reservations 42
200 GET     /room_types         -> listing all room_types
200 GET     /room_types/7       -> showing room_types 7
405 PATCH not allowed on /reservations
405 DELETE not allowed on /reservations
handled 6, refused 2, total 8
reconciled: true
  200 x6
  405 x2

Not one of those eight requests named a method. GET /reservations/42 became Controller#show because the verb was GET and the path had a second segment; POST /reservations became Controller#create because the verb was POST and it did not. The mapping lives entirely in action_for, and ctrl.send(action, ...) turns the resulting string into an actual method call -- which is how Rails dispatches, and also why an action name you did not expect becomes a method call you did not write. The two 405 lines are requests whose verb-and-shape combination has no convention: PATCH was never mapped, and DELETE without an id has nothing to destroy.

The arithmetic closes. Six handled plus two refused is eight, which is the request count, so reconciled: true is a claim about the numbers rather than the formatting. The by_code tally is derived by grouping on the first three characters of each result and is printed in sorted order, so 200 precedes 405 deterministically rather than depending on hash iteration order.

The design has a real flaw, and it is the same send that made the whole thing work. action_for is a closed whitelist today, but the moment someone "simplifies" route to derive the action straight from the verb and call ctrl.send(params[:action]), the router will call any method name an attacker puts in the path -- inspect, instance_variable_get, or worse. Rails guards against exactly this by dispatching only to actions the controller has explicitly declared public, and by matching routes against a compiled table rather than sending arbitrary strings. Three narrower faults sit alongside it: resource is used to build the response but the code never checks that a controller for it actually exists, so GET /nonsense would happily "list all nonsense"; the singular-versus-plural convention is quietly dropped, so the output reads "creating a reservations"; and id is passed through as the raw string from the path with no type check, so show("42") and show("../etc") are treated identically.


Common Mistakes

  1. Naming a table against the convention and then fighting Rails about it. Create a table called reservation (singular) or policys (wrong plural) and Rails will look for reservations or policies and report a missing table. The fix is not self.table_name = on every model; it is to name the table the way the inflector expects, so the next developer does not have to learn your exceptions.
  1. Reaching for configuration before learning the convention. Every setter like self.table_name, foreign_key:, and class_name: is a deviation sheet. Each one is a small note that says "this model does not follow the manual", and every note is something a future reader must find before they can trust the defaults. Override only when the domain genuinely demands it.
  1. Skinny models and fat controllers. The convention is that business logic lives in the model and the controller only translates between HTTP and the model. Controllers that validate, calculate, and format are the single most common way a Rails app becomes hard to test, because logic reachable only through a fabricated request cannot be unit-tested.
  1. Treating a generator's output as finished code. Scaffolding writes a controller, views, and a migration from the model name in seconds, but it writes the generic version. Shipping scaffold output unread is how apps end up with actions nobody needs and views that expose every column, including the ones that should never reach a browser.
  1. Callbacks that reach outside the database. An after_save that sends an email or calls an external service ties a network round-trip to every write, so a slow mail server makes saving a record slow, and a failed charge inside a save callback can roll back data that was actually valid. Side effects that are not the record's own state belong in an explicit service call, not a lifecycle hook.
  1. N+1 queries hidden behind convenient associations. Looping over reservations and reading reservation.room_type.name inside the loop issues one query per reservation. The association makes the extra queries invisible in the code, so the page is fast on ten rows in development and collapses on ten thousand in production. Load the association up front with includes when you know you will read it.
  1. Putting request-shaped logic where it cannot be reached in a test. Reading params or session deep inside a model method drags the whole HTTP machinery into code that should be testable with plain objects. Pass the values in as arguments; keep the model ignorant of how the request was shaped.
  1. Mass assignment without a permit list. Handing raw request parameters straight to update lets a caller set any column, including admin or account_balance, by adding a field to the form. The convention is to name the permitted attributes explicitly, and skipping it is a data-integrity hole disguised as brevity.
  1. Assuming convention means the framework will catch your mistakes. Convention wires things together; it does not validate them. A misspelt association name, a route to an action that does not exist, or a view that reads an attribute the query never loaded all pass silently at boot and fail only when that exact path runs. Convention reduces typing, not testing.

Best Practices

  • Learn the conventions before you learn the configuration. Almost every setter in a Rails model exists to opt out of a convention, and you cannot judge when to opt out until you know what the default gives you.
  • Name for the inflector. Choose model names whose plural the standard inflector already knows, and check an irregular one before you write the migration rather than after the missing-table error.
  • Keep controllers thin. A controller action should read the request, call one model method, and choose a response. Anything longer is logic that wants to be in the model where a test can reach it.
  • Put domain logic in the model and keep it ignorant of HTTP. A model method that takes plain arguments and returns plain values can be tested without a request, which is most of what makes a Rails codebase pleasant to change.
  • Treat generated code as a first draft. Read every line the scaffold wrote, delete the actions you do not need, and narrow the views to the columns that should be public before the code ships.
  • Load associations you know you will use. When a view iterates over records and reads a related object, name that association in an includes so one extra query serves the whole loop instead of one query per row.
  • Permit attributes explicitly. List the fields a request is allowed to set, so adding a sensitive column to the table does not silently make it writable from a form.
  • Let the environment files be pure deviation sheets. Put every shared value in the defaults and let each environment declare only its differences, so a change to a default moves every environment that did not deliberately opt out.

Practice Exercises

  1. Extend the inflector. Add irregular plurals to the pluralise method from the Technical Depth section so that person becomes people and analysis becomes analyses, while the regular rules still handle reservation and policy. Prove with output that the irregular words take the new path and the regular words are untouched.
  1. Route a new verb. Add PATCH /reservations/:id to router.rb so it maps to an update action by convention, implement update on the controller, and show that the previously-refused PATCH request now returns 200 while DELETE /reservations is still correctly refused.
  1. Close the send hole. Change route so it dispatches only to a fixed set of allowed action names and returns 403 for anything else, then demonstrate the flaw the original had by feeding it a path whose second segment is a method name like inspect and showing the two versions behave differently.
  1. Add the missing convention. The router prints "creating a reservations" because it never singularises the resource. Write a singularise helper, apply it in show, create, and destroy, and show that the output now reads "creating a reservation" while the listing action still speaks of "all reservations".