Rails generators are pure magic: we use them to create the basic framework for our rails apps so that we don't have to undergo the tedious exercise of creating the structure ourselves. There are 5 basic commands we use quite frequently that fall at various levels of abstraction. We choose to use one over the other depending on the level of complexity our models require. Although there are plenty of resources online that document rails generators and how to use them, I I couldn't find a single consolidated cheat sheet anywhere on the web. I've created a chart below that has already mitigated some of the confusion for me, so I wanted to share it with you, dear reader.
In order of abstraction from least to greatest the commands rank as follows:
- rails generate migration
- rails generate model
- rails generate controller
- rails generate resource
- rails generate scaffold
And the table below documents what you can expect to be created for you when you use each one:
Command | Syntax: Model name + ? | Model | Migration | Controller | Views | Test Suite | Assets (Javascripts, Stylesheets) | Route in config file | Helper |
---|---|---|---|---|---|---|---|---|---|
Migration | attributes as name:type | N | Y | N | N | N | N | N | N |
Model | attributes as name:type | Y | Y | N | N | model | N | N | N |
Controller | views | N | N | Y | Y | controller | Y | Y | Y |
Resource | attributes as name:type | Y | Y | Y | folder; no files | controller, model | Y | N | Y |
Scaffold | attributes as name:type | Y | Y | Y | Y | controller, model | Y | Y | Y |
Don't forget, if you ever choose the wrong one and want to undo, you can use the rails destroy command. For example, if you created a scaffold for Becca but realized you only needed a controller, you could execute:
rails destroy scaffold becca
rails generate controller becca index show
Just remember that it will remove any and all files related to your Becca model, so use with caution.
:)