Rails Generators Cheatsheet
One of the really cool bonuses of using Ruby on Rails rather than fully writing out everything is Ruby is the ability to use generators. Rails has several types of generators that I will be creating a cheatsheet for here. Generators have an added bonus of eliminating syntax errors and typos because certain pieces are done for you.
Types of Generators
migration
model
controller
resource
Syntax
rails g <type of generator> <options>
rails: the beginning of any rails command
g: stands for generator (you can write out generator if you prefer)
<type of generator>: choose from the list above
<options>: this is where you can customize your generator
Migrations
examples:
Adding a column to schema (remember to run ‘rails db:migrate’ after running this command)
rails g migration add_column_name_to_model_name column_name:data_type
Removing a column from schema (remember to run ‘rails db:migrate’ after running this command)
rails g migration remove_column_name_from_model
Models
This creates the database migration that will add the table and columns for the listed attributes as well as a model file. You can add multiple attributes by just adding a space between each one.
example:
Adding a model
rails g model Model_Name attribute_name:data_type
Controllers
This creates a lot of different items for you:
- The controller file
- A new directory for all of the view templates as well as the template for each file of the controller actions
- A view helper method file
- Routes for each of the attributes that were added in the generator command
Times a controller generator is useful:
- Adding non-CRUD related features
- Static views
example:
Adding a controller
rails g controller controller_name attribute_name:data_type
Resources
Files that will be created:
- The controller file
- A new director for all of the view templates without the view files
- A view helper file
- Full set of routes resources
- Migration file that will create the new database table for the requested attributes
- Model file
Times a resource generator is useful:
- When using a front end MVC framework
- When building an API
- You don’t like the view files created by the controller generator and want to start them from scratch
example:
Adding a resource
rails g resource Model attribute:date_type
I hope this is a helpful cheatsheet. This is what I use when I am trying to remember which type of generator I want to run and how to set it up without having to delete and redo everything. As always, please also refer to official documentation periodically to be see if there are any updates and new features added to help make life easier.