DEV Community

Cover image for Rails Generators
Ben Perry
Ben Perry

Posted on

Rails Generators

We are finishing up our Rails curriculum at Flatiron School this week and I wanted to make a post about different generators Rails offers us. Generator commands take simple tasks like creating boilerplate code for your backend project and produce multiple template files almost immediately. I'd like to go over the differences of a few that I've used on every project.

To start, you can see a list of available generators with the simple command. Note: you can shorten these commands by typing rails g instead of rails generate.

rails generate

console output from rails generate

Here are a few that I have been using the most.

Create a Migration file

rails generate migration Table_name column_1 column_2:boolean column_3:integer

With this command you can name your table and optionally input all your column names with data types and get that out of the way with 1 simple terminal command! Any column name not given a data type will default to string.

Create a Model and Migration file

rails generate model Table_name column_1 column_2:boolean column_3:integer

This command will create both a migration and a model file.

Create a Controller file

rails generate controller Controller_name

This command will create a controller file for your model.

Create a Resource file

rails generate model Table_name column_1 column_2:boolean column_3:integer

This is a great generator that does a lot of work for you with one simple command. Thanks Rails! This produces a migration, a model, a controller, a resources method for all of the restful routing for your model, views for the model, a serializer, and some test files. Wow all that with one simple command.

Remove the files

rails d resource Table_name

If you made a typo or a table that you don't want anymore you can easily remove all the files created with your generator with this command to make sure everything is cleaned up nicely.

Top comments (0)