Ruby on Rails Generators

Maria Coitinho
7 min readDec 31, 2022

--

Building a Ruby on Rails backend API from scratch using boilerplate code can be a very hard task. If you are familiar with Ruby language used with the Rails gem to simplify the creation of backend API servers, in this post I will be unpacking one of Rails most powerful tools for that purpose: generators.

Creating a Rails API through the command line interface ($ rails new rails_application_name) is already a great tool itself, which sets up various backend files and directories, giving them a pre-built code and establishing name conventions.

Rails application set up

If you don’t have Rails yet, you can do it using the following command available with RubyGems:

$ gem install rails

Still in your command line, you can check for your current rails version:

$ rails -v
Rails 7.0.4

Great. Having rails ready, let’s start by configuring and generating the most essential files for a RESTful API that in the future will be able to receive code that responds to CRUD client requests made with HTTP verbs:

  • Create → POST HTTP request;
  • Read → GET HTTP request;
  • Update → PATCH/PUT request;
  • Delete → DELETE request

Configuring your API properly using built-in Rails tools that choose convention over configuration, will save you a lot of time when debugging, preventing errors.

For this post I am going to use a practical example of an API: a server that contains data of a flowers store.

However, we won’t be writing all of the code by scratch to map between routes, controllers and models. We will simply be using a generator to create all the functionality and association that we need.

First, we are going to create our rails application through the command line:

$ rails new flower-store

Then, navigate to the flower-store directory.

Rails generators

Before hopping into our flower store example, which we will be creating with the resource generator in the end of this post, let’s go over some examples of Rails generators. Rails itself has great helping texts on its console utilities. In the flower-store rails app directory we can run:

$ rails --help
# or
$ rails -h

The help flag will display the most common rails commands used, along with others (not displayed):

We notice that the first command listed is the one we will be working with, generate.

Now, we can check what different kinds of generate options we have, running the command:

$ rails g -h

We will get back a list of generators:

We will be covering on this post: controller, model, migration and resource.

generate controller

Each generator automates a specific task of creating, editing files and other helpful functionalities for setting up the Rails API. For example, if we want to create a controller for our flower-store app, we can do so:

$ rails g controller Flowers

We can even check how the controller command syntax works through the terminal, using once again the -h flag:

$ rails g controller -h

If we check the returning helper text, we have:

Above, Rails is giving us the template for the generate controller command:

$ rails generate controller name_of_controller [action]

Rails also shows a description about the controller generator, which is very helpful:

Let’s use all of this information given from rails, to create a flowers controller:

$ rails g controller Flowers

Note: Make sure that you check the helper texts to follow naming conventions when using the generators. For example, above we used upper camel cased letters on plural, but we could have also achieved the same goal with snake cased syntax.

The command will create a new file called flowers_controller.rb, that inherits from ApplicationController:

In the controllers directory, we can check where the ApplicationController comes from: it is a subclass of ActionController::Base and is located in a file already set up by Rails. This file the only one that inherits from ActionController::Base, which is responsible for handling client requests and performing actions:

Nice, we now have our controller set up. But, what if we want to undo the command? We can simply run:

$ rails d controller Flowers

The ‘d’ stands for delete, so we are deleting the controller and passing its name given upon creation.

generate model & generate migration

Now let’s try a different generator: model. As the name already says, the model generator creates a model file in its proper directory, along with a migration file:

$ rails g model Flower

Running the command above (notice that the model name is on singular by convention), we have:

We can check the logs of any generator in the console once the command in ran. In the model, we see that Active Record created a migration file in the proper db/migrate directory and also a flower.rb model file in app/models.

Note: When we use generate, it will invoke the test_unit and create some files automatically. These are system tests that allows us to test user interactions with our application.

To visualize that our files were properly created, navigate to their own directories to check each of them:

model file
migration file

Our model generator created both files and set up the create_table method in our migration, so we can add columns and data types to our table. We can even generate a model already passing the table columns attributes and also use a flag to specify if we don’t need the system tests to be installed:

$ rails g model Flower name species price:integer --no-test-framework

Above we are generating our model, giving the tables columns names that will be mapped by the model. Each table column as we know, need to have a data type defined. If we are not giving any type for the column name, it means that it’s a String by default — notice that we had to specify the price data type as it is not a String.

For the migration generator it works similarly but instead of creating both model and controller files, it will only create a migration file. Although, you can still specify the table attributes:

$ rails g migration CreateFlowers name species price:integer

Above we can see that it was created a new migration file with its time stamp and snake-cased name by convention. Let’s check the file:

We have successfully created our migration with the generate command, along with its table structure. Great!

Note: Remember that you can always undo each generate command copying it and replacing the ‘g’ for ‘d’ of delete, so you can go trough each generator examples in this post.

generate resource

The resource generator is the most powerful one: with only one command it generates a model, controller, migration, views directory and optionally routes.

With resource, we will be finally creating all the files for our flower store data API, with a single line! Check it below:

$ rails g resource Flower name species price:integer

Wow! Many files were created with this command. From the top line of the log generated and going down, we have created:

  • Model and migration files;
  • Rails system test files;
  • Controller file;
  • Views directory and its respective file;
  • Route file.

Next, check each of these changes in their respective directories given by the paths. Now you can start coding in your backend API some functionalities to handle client requests!

Conclusion

Rails gem is becoming more and more popular around developers due to its facility to create structured API backends. Along with Rails preference of convention over configuration, we don’t need to worry about setting up and memorizing all naming conventions and accidentally break our application.

With Rails generators, we are able to:

  • Give our application commands through the command line, without going directly to a file and modifying it;
  • Create pre-configured files with single line commands using generators like controller, model, migration and resource;
  • Use the resource generator to create different API files (model, migration, controller, views, route);
  • Save time configuring our application;
  • Prevent errors and bugs.

--

--