DEV Community

javier
javier

Posted on

Using rails generator to create you table models

Ruby on rails makes creating table models super easy. In order to create a table model, you need to first go into your terminal. Start the command with:

rails g
"g" stands for generate. After you create your table, you have to name it. For example, if I wanted to created a table for restaurants I would type in something along the lines of:
rails g model Restaurants

Next, you'll add your columns. Continuing with the restaurant example, most restaurants have a name, store number, and address. To add this information, just type in:
rails g model Restaurant name store_number:integer address
rails by default rails will assume you want your column to be a string so you won't have to type anything after you've named your columns. Saying that, you'll notice that for store number I added :integer. If you want your column to be something besides a string, you'll have to specify that.
After that, you should get this in your terminal:
Image description
then check your app file, go into models, and your restaurant.rb should be there. Also go to your db file, then into migrate; your migration should be there all set up like so:
Image description

Rails has many more generators that can be useful. This just the tip of the iceberg. This probably my favorite part of rails. It makes coding a lot faster and more efficient. Let us focus on more complex and personalized code.

Like even creating the whole MVP. Using the resource generator not only creates your model but also your controller, your serializers , and your routes. Not including your associations. Which will set up your micros in your table that connects with other tables or your belongs_to but you will have to set up your has_many on your own.
The best part being that it is super easy to fallow and learn. So need to worry if it be hard to learn or not or even worth your time. Which obviously it is most definitely worth it.
You can find all the information ruby has great guides so I definitely recommend looking into the guides.

Top comments (0)