0
0
RailsHow-ToBeginner · 3 min read

How to Create a Model in Rails: Simple Guide

To create a model in Rails, use the rails generate model ModelName field1:type field2:type command in your terminal. This creates a model file and a migration to define the database table structure.
📐

Syntax

The basic syntax to create a model in Rails is:

  • rails generate model ModelName field1:type field2:type

Here, ModelName is the name of your model (singular and capitalized), and field:type pairs define the database columns and their data types.

bash
rails generate model Product name:string price:decimal
💻

Example

This example creates a Product model with name as a string and price as a decimal. It generates a model file and a migration file to create the products table.

bash
rails generate model Product name:string price:decimal

# Then run migration to update database
rails db:migrate
Output
Running via Spring preloader in process 12345 invoke active_record create db/migrate/20240601000000_create_products.rb create app/models/product.rb invoke test_unit create test/models/product_test.rb create test/fixtures/products.yml == 20240601000000 CreateProducts: migrating ===================================== -- create_table(:products) -> 0.0012s == 20240601000000 CreateProducts: migrated (0.0013s) ============================
⚠️

Common Pitfalls

Common mistakes when creating models include:

  • Using plural names for models instead of singular (e.g., Products instead of Product).
  • Forgetting to run rails db:migrate after generating the model, so the database table is not created.
  • Not specifying field types correctly, which can cause migration errors.
bash
rails generate model Products name:string
# Wrong: model name should be singular

rails generate model Product name:string
rails db:migrate
# Correct: singular model and migration run
📊

Quick Reference

Summary tips for creating models in Rails:

  • Model names are singular and capitalized (e.g., User, Order).
  • Field types include string, integer, decimal, text, boolean, datetime, etc.
  • Always run rails db:migrate after generating a model.
  • Use rails generate model to create both model and migration files automatically.

Key Takeaways

Use singular, capitalized names for Rails models.
Run 'rails generate model ModelName fields' to create model and migration files.
Always run 'rails db:migrate' to apply database changes.
Specify field types correctly to avoid migration errors.
Models represent database tables and handle data logic in Rails.