The Rails Command Line and Generators
A Rails developer spends a surprising amount of time in the terminal: starting the server, running migrations, poking at data in a console, and generating files. One entry point covers all of it, and generators make sure new files are born with the right names in the right folders.
The rule
bin/rails runs the app's tasks; generate writes the boilerplate.
The everyday commands:
bin/rails server # start the app (short: bin/rails s)
bin/rails console # a Ruby prompt with your app loaded (bin/rails c)
bin/rails db:migrate # apply new migrations
bin/rails db:rollback # undo the last migration
bin/rails routes # list every route
bin/rails test # run the test suiteGenerators come in sizes:
bin/rails generate model Book title:string pages:integer
bin/rails generate controller Pages home about
bin/rails generate scaffold Book title:string pages:integer- model: the model class, a migration and tests.
- controller: the controller with the listed actions, a view for each and matching
getroutes. - scaffold: everything for a resource — model, migration, controller with all seven actions, views, routes and tests.
bin/rails g is short for generate, and bin/rails destroy model Book deletes what the generator made. Generators follow naming conventions for you: a model is singular (Book), its table and controller are plural (books, BooksController).
The shortcut
Before generating, ask "how much of the stack do I need?" Just data → model. Just pages → controller. The full create-read-update-delete set → scaffold. Then remember: a migration is only a file until you run db:migrate.
Choose the size
Bookclub needs books stored and listed, edited and deleted, so scaffold fits.
The trap is running the server right after generating and hitting a "pending migration" error. Generate, then migrate, then serve.
Drills
Answer fast — trust the rule.
Which command opens a Ruby prompt with Bookclub's models loaded?
What does bin/rails generate model Book title:string NOT create?
You generated a model and your first page load says a migration is pending. What do you run?
A scaffold for Book creates a controller with what name?
Remember
- bin/rails runs the app's tasks; generate writes the boilerplate; destroy removes it.
- Shortcut: model for data, controller for pages, scaffold for the whole resource.
- Trap: generate, then migrate, then serve.
