Rails g Makes It Easy

Anthony Banks
3 min readJul 14, 2021

Ruby on Rails is an incredibly efficient framework for Ruby. Everything I can think of has an easier, more direct, and far less time consuming way to produce the same result.

For instance, Ruby on Rails makes the “M” and the “C” of MVC incredibly easy with a simple command in your terminal, “rails g …”. I’ll go over the two most common uses of rails g, “rails g model” and “rails g controller”.

Rails g Model

The “g” in rails g stands for generate, so in this instance rails g model is literally rails generating a model for you based off of your specifications. Here I’ll give an example:

After executing this command, a table named persons will be added to the database with two columns; name and age. The last part, “ — no-test-framework”, is just a flag to prevent auto-generated tests forming for your model. It’s not necessary though so don’t worry too much on that. The first argument is the name of the model, naming conventions require this to be capitalized and singular. Arguments following the name are fields that the model contains. In this example Person will have two fields, name and age. After naming the fields, the type can be changed by putting the type after a colon. The name will have the type “string” and the age, with the type “integer” will be an number. Now you have a model ready to migrate!

Rails g controller

Next is the controller generator. A controller essentially gives the database direction on what its meant to do with any request it gets sent, and no controllers are as efficient to produce as rails controllers. To start it off lets make a controller for our person model. The command would look like this.

Very similar to the model generator command except here we make the controller name plural as per naming conventions. This command will add a controller to your database where you can define what your routes will do. For example if you wanted the database to return every person whenever it received a get request to persons, you would define a method in the persons controller that would render all of the persons in your database. That method could look something like this.

Rails has many more generators that are all equally useful. Just goes to show how efficient it is to work in this framework.

--

--