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).
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
To create the metadata for your model, including all class attributes as columns, type,
To create the actual database, now type,
To check the database, type this,
Then, to see the tables you creates, enter,
In this case, you created a table called
The see the schema of the posts model, type,
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].