Creating an app and its conventions

Ruby on Rails · Essentials · 10 min

Rails' conventions are the framework: knowing them tells you where everything is and what you get for free.

Install Rails with gem install rails and create an app with rails new blog. Rails 8 defaults are deliberately simple: SQLite in every environment, Propshaft for assets, importmap for JavaScript without a Node build step, Hotwire (Turbo and Stimulus), and the Solid trio (Solid Queue, Solid Cache, Solid Cable) backed by the database. It also generates a Dockerfile and Kamal config for deployment, plus RuboCop, Brakeman and a CI workflow.

Run bin/dev (or bin/rails server) and open http://localhost:3000.

The layout follows MVC:

  • app/models, app/controllers, app/views: the three layers. Also app/jobs, app/mailers, app/helpers and app/javascript.
  • config/routes.rb maps URLs; config/database.yml configures the database; config/credentials.yml.enc stores encrypted secrets.
  • db/migrate and db/schema.rb hold the schema; test/ holds tests; bin/ holds binstubs like bin/rails.

Convention over configuration means names line up automatically: the Article model maps to the articles table, ArticlesController renders views from app/views/articles/, and app/models/line_item.rb defines LineItem. Follow the conventions and you write almost no glue code.

Generators create files that follow them: bin/rails generate scaffold Article title:string body:text produces a migration, model, controller, views, routes and tests. bin/rails console opens an IRB session with the app loaded.

Example

gem install rails
rails new blog            # SQLite, Hotwire, Propshaft, Solid Queue/Cache/Cable, Kamal
cd blog
bin/rails --version       # Rails 8.0.x

bin/rails generate scaffold Article title:string body:text published:boolean
bin/rails db:migrate
bin/dev                   # http://localhost:3000/articles

bin/rails console         # IRB with the app loaded
# >> Article.create!(title: "Hello", body: "First post")
# >> Article.count  # => 1

bin/rails routes -g article   # routes matching "article"
bin/rails test                # run the test suite

Remember

  • rails new gives a complete, production-ready stack with database-backed defaults
  • Names connect layers: Article -> articles table -> ArticlesController -> views/articles
  • Generators and bin/rails console speed up everyday work

Watch out for

  • Fighting conventions (custom table names, odd file names) and then writing glue code Rails would have made unnecessary.

Check yourself

  1. Following Rails conventions, which table does the model LineItem use?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: guides.rubyonrails.org/getting_started.html