Helpful Rails Generator Commands, Understanding the differences

Rails generate commands can make a coders project less tedious by building the basic model, controller, and migrations format for them. Using these generators will save you development time, minor mistakes and help you be more efficient.

The rails generate command can be used with ‘generate’ or ‘g’

rails generate

or

rails g

Most helpful rails command

rails g model
rails g controller
rails g resource
rails destroy
rails g -h

Rails generate model

rails g model super_hero

The rails generate model command can create the projects model and its migration. The model will be set up with it’s inheritance so you can have full ActiveRecord methods. It will also create the migration table and you can input the column names and data types in the migration file.

rails g model super_hero name:string power:string age:integer

But you can also add the migration table column name and data type in the same line and get it all done in one command

Rails generate controller

rails g controller super_heros

The rails generate controller command can create your projects controllers and a view folder for it as well. You can also add to the controller command to create the controller actions and the related html.erb file in the views folder. When you add the controller actions it will also create basic routes for you in the /routes.rb file.

rails g controller super_heros index new show

Rails generate resource

rails g resource super_hero name:string power:string age:integer

Since we looked at how to create a model and controller separately now lets do it all at once. ‘rails generate resource’ will do everything ‘rails generate model’ did but also will create the controller and a view folder for that controller. It will also create the resource in the /routes.rb file for you. One thing the generate resource command doesn’t do is create the controller actions and view pages, if you use resource, you’ll need to add those in.

Rails destroy

So being able to do all of these helpful commands are great but what if you have some typos or what if you change your mind about one of the models, then what? well, theres another rails command that’ll help a lot. just like rails generate, rails destroy also has an alias, ‘rails d’. when using rails destroy you can destroy a model or controller you just created.

rails d resource super_hero

Rails generate help syntax

You can always look to see what other generators are there for you to take advantage of.

rails g -h

Currently Studying to be a Software Engineer At Flatiron.