DEV Community

Andrea Esparza
Andrea Esparza

Posted on

Basics of Rails Generators

Rails generators have become common practice for me since we started learning Rails because they have streamlined the process of creating files. The purpose of this blog is to have a descriptive list of the different generators available. Above all, Rails generators are terminal commands. If you follow their rules and conventions, you will be able to use them efficiently.

Set Up

Before you start typing terminal commands, it's important to know what you are going to create. If you are creating a table, make sure you know the name of the table, the names of the columns, and the datatype for each column. While it's not obligatory to write out every piece of information in the terminal, it does make it more efficient. For each table we follow our MVC - Model, View, Controller. Therefore, we will be creating a model, a controller, and a serializer for each table.


The first generator on the list is the model. This needs to be first because it's the piece of the puzzle that sets up our table and its columns. To create the model, run this command:
$ rails generate model table_name column_a:datatype column_b:datatype and so on. This command also creates the migration that goes with the model.

One of my favorite things about Rails is that it lets us use 'g' instead of typing 'generate.' It also sets the default datatype to be string, so you don't need to specify that one. All other datatypes need to be specified.


The controller is the middle-person between the model and the view. We can create it using a rails generator as follows:
$ rails g controller table_name


For the view side of things, we use serializers. Therefore, we will use this command:
$ rails g serializer table_name

There's gotta be another way...

There is! When you are setting up a Rails application and you know that you're going to need a model, a controller, and a serializer, we can use a resource generator.


The resource generator takes care of creating a model, a controller, a serializer, a migration, a test suite, and adds the route. The command looks like this:
$ rails g resource table_name column_a:datatype column_b:datatype

What if I mess up?

If you make a mistake or need to redo any of these generators, we can use the drop command as such:
$ rails drop [generator] table_name
The generator depends on what you need to drop, whether it be a model, a controller, a serializer, or a resource. And again, Rails lets us use 'd' instead of the word 'drop.'

Final thoughts

  • Rails generators are a way of creating files through the terminal, but it doesn't mean it's the only way of doing things.
  • At Flatiron, we've learned to add --no-test-framework at the end of our rails generator commands so we don't mess with the existing test suites.

Top comments (0)