DEV Community

Cover image for Rails Generators: Model or Resource?
R-Villar
R-Villar

Posted on

Rails Generators: Model or Resource?

Rails is a powerful tool for a developer, you can do so much with just a few keystrokes in the command line. When you first learn about generators the one thing that goes through your mind is "This will make my life so much easier", And it will. But this is the moment when you should take a step back and try to understand why and how will this magical generators will change your life. First you need to know what they are.

What are Generators??

Rails generators are command line tools that are used for automating the process of creating or editing files with boiler plate code. In essence, they execute Ruby code much like a script and create or update files based on templates, user input and whatever logic necessary.

Now that you know that lets run some generators!

In the command line, you can type rails generate or rails g these will both get you the same result. Running this by itself will give you a list of available generators.

Image description

and much more.

Let's generate some code.

We will begin by creating a migration.

Running this code rails g model car name brand model year:integer trim

Image description

This will create a migration a model and some test.

Image description
Image description

This is great! we were able to get all that from just one line of code in the terminal.

What if we can get even more done from the terminal? make this even easier! that where resource come in! by just changing the command we ran before from model to resource rails g resource car name brand model year:integer trim

We get even more! migrations, models, test, controllers, routes and serializer.

Image description

If you are starting to get a bit overwhelmed, well it is.
This is the time that you as a developer need to stop and think, generating all that code for you is amazing! It will improve your work flow but if you are still new to rails and generators this is where you need to slow down. Understanding what is happening with the code you generate is very important, it will help you debug your code when something goes wrong. Key word is when not if, we will all make mistakes while writing code.

Shortcuts have no place in programming, besides wouldn't you want to understand all that magical code you write.

generators

Top comments (0)