How Are Models Generated on Ruby on Rails?

If, like me, you are starting to learn Rails, you will run into the need to generate models.

In this post, I show a simple example of how to create a model for a simple blogging site.

First, the model design must be ready to be created. In this example, let’s create the code to generate a blog summary page.

In this project created on Rails, the selected model will hold the Posts for the blog. Each Post must contain a string value as title, a text value as the post content, and the creation date (date time type).

After installing Rails, and the project creation, you’ll find the command line executor in the project folder.

Once you get the command line shell running, generate the model for a Post by typing this command,

rails generate model Post title:string content:text created_at:datetime

And this is the result,

BTW, if you don’t have the right permission, run the command with sudo permission.

After the command runs, the model will be found in app/models in the Rails directory. It should look like this,

class Post < ApplicationRecord end

To create the metadata for your model, including all class attributes as columns, type,

db:migrate

To create the actual database, now type,

rails db:setup

To check the database, type this,

sqlite3 db/development.sqlite3

Then, to see the tables you creates, enter,

.tables

In this case, you created a table called posts.

The see the schema of the posts model, type,

.schema posts

as in the image below.

As you can see, the model schema that we created is the same than the table on database, only the id field is added.

In a future post, I will talk about the Rails generators in in a more general way.

In the meantime, if you have any questions, please contact me [email protected].

Focus Mode

Contact Request

Close

We will call you right away. All information is kept private