0
0
Ruby on Railsframework~5 mins

Model generation in Ruby on Rails

Choose your learning style9 modes available
Introduction

Model generation creates a blueprint for your data in a Rails app. It helps you organize and store information easily.

When you want to create a new type of data to save, like users or products.
When you need to set up how data connects to other data in your app.
When you want Rails to help make database tables and code for you automatically.
Syntax
Ruby on Rails
rails generate model ModelName field1:type field2:type

Replace ModelName with the name of your data model, usually singular and capitalized.

Specify fields with their data types, like name:string or age:integer.

Examples
This creates a User model with name and email fields as strings.
Ruby on Rails
rails generate model User name:string email:string
This creates a Product model with title as a string and price as a decimal number.
Ruby on Rails
rails generate model Product title:string price:decimal
This creates an Article model with title, body text, and a published true/false field.
Ruby on Rails
rails generate model Article title:string body:text published:boolean
Sample Program

This example shows how to generate a Book model with three fields. After running the command, Rails prepares the code and database changes needed. Running rails db:migrate applies the changes to your database.

Ruby on Rails
rails generate model Book title:string author:string pages:integer

# After running this command, Rails creates:
# - A Book model file
# - A migration file to create books table with title, author, and pages columns

# To apply the migration and create the table, run:
rails db:migrate
OutputSuccess
Important Notes

Model names should be singular and capitalized, like User or Book.

Data types include string, integer, text, boolean, decimal, and more.

Always run rails db:migrate after generating a model to update the database.

Summary

Model generation creates a data blueprint and database setup in Rails.

Use rails generate model with fields and types to define your data.

Run migrations to apply changes to your database after generating models.