Model Generator in Rails

Shaqqour
2 min readDec 24, 2020
Photo by Joshua Aragon on Unsplash

Rails comes with a built-in script called Generator. It can produce many rails items that are necessary in every web/mobile application such as Models, and Migration. In this blog I will be explaining the Model Generator, how to use it, and how to customize it.

Model Generator

Model generator is one of the most common generators in Rails. Here is the command for the simplest one:

rails generate model Test

This command will generate a model called Test “app/models/test.rb” that has no attributes/class variables. The model will look something like this:

class Test < ApplicationRecordend

It will also create an empty migration for the Test Model, so that when you run it, it will create the actual table for this model. The migration file “db/migrate/create_tests.rb” will look similar to this:

class CreateTests < ActiveRecord::Migration[6.0]
def change
create_table :tests do |t|

t.timestamps
end
end
end

Then inside the change method, you will have to add each of the table attributes and specify what data types they will be:

class CreateTests < ActiveRecord::Migration[6.0]
def change
create_table :tests do |t|
t.string :first_name
t.string :last_name
t.string :email
t.timestamps
end
end
end

There is also an alternative way in which you don’t have to code those attributes. You will just have to specify each one in the beginning once you run the model generator. So if you want to create the previous Test model here is the the generator command to do so:

rails generate model Test first_name:string last_name:string email:string

This generator will create the same two files, test.rb and create_tests.rb, except that the migration file will have these attributes.

This was how to use the Model Generator in Rails. Watch out for my next blog posts on other rails generators. If you have anything you would like to add, please comment below.

--

--

Shaqqour

Full stack software engineer. Passionate about making people’s lives better and easier through programming. LinkedIn.com/in/shaqqour