Rails Generators
Applications can be large, very large. Using Ruby on Rails for example there is the standard MVC (Model View Controller) structure. The larger the application is, the more files need to be created. Now there is the option to manually create all the appropriate files by hand, and this old-fashioned method is something that everyone should be familiar with, but Rails has build in generators that make building out applications much easier.
All generators in Rails begin with the CLI command ‘rails generate’ or simply ‘rails g’ after that you can simply type in what you want to generate beyond that.
- Models
Let’s pretend we want to generate a Cat class for our application (not sure why cats was the first to come to mind)
rails g model Cat
Make sure the model name is capitalized.
This will create a cat.rb file in the models folder as well as a migration file in the db/migrate folder.
Now just typing this will create the migration file but it won’t have any columns, those will have to be typed by hand. If we wanted to create the columns using the same generator, we just have to add more to the terminal.
Using the previous cat example, a template for that looks something like:
rails g model Cat column1:data_type column2:data_type
So on and so forth
So in the cat context:
rails g model Cat name:string breed:string bio:text
2. Migration files
If we wanted to add an addition column to an existing table:
rails g migration add_column_name_to_table_name
make sure to use underscores to connect all the words.
If we want to add the data types all in one go:
rails g migration add_column_name_to_table_name column_name:data_type
We can also use generators to remove columns if needed:
rails g migration remove_column_name_from_table_name column_name:data_type
Models and migration files are pretty common to generate using Rails, but could we do it in one fell swoop?
Of course we can!
3. Resource
To create a model file, migration file, a controller, and even routes in the routes.rb file, Rails can generate a Resource. Make sure the class name is capitalized. Using the cat example one last time.
rails g resource Cat name:string breed:string bio:text
This really fills out our MVC structure. Complete with a Cats Controller, model file, migration file, and all the CRUD routes in the routes.rb file.
Rails generators are a very useful tool to make filling out any application easier. Learning how to use them saves time and makes coding more efficient.