Bird
Raised Fist0
Ruby on Railsframework~10 mins

Model generation in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Model generation
Run model generator command
↓
Create model file with class
↓
Create migration file
↓
Edit migration if needed
↓
Run migration to update DB
↓
Model ready to use in app
The flow shows how running the Rails model generator creates files and updates the database schema step-by-step.
Execution Sample
Ruby on Rails
rails generate model Article title:string body:text
rails db:migrate
This command creates an Article model with title and body fields, then updates the database.
Execution Table
StepActionFile Created/ModifiedContent SummaryResult
1Run 'rails generate model Article title:string body:text'app/models/article.rbDefines Article class inheriting from ApplicationRecordModel file created
2Run 'rails generate model Article title:string body:text'db/migrate/XXXXXXXXXXXXXX_create_articles.rbMigration file to create articles table with title:string and body:textMigration file created
3Edit migration file (optional)db/migrate/XXXXXXXXXXXXXX_create_articles.rbAdd/remove/change columns if neededMigration file ready
4Run 'rails db:migrate'Database schemaCreates articles table with specified columnsDatabase updated
5Use Article model in appapp/models/article.rbModel connected to articles tableModel ready for use
💡 All files created and database updated, model generation complete
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
Model fileNoneCreated with Article classUnchangedUnchangedReady
Migration fileNoneCreated with create_articlesEdited if neededExecuted to update DBApplied
Database schemaNo articles tableNo changeNo changeArticles table createdUpdated
Key Moments - 2 Insights
Why do we need to run 'rails db:migrate' after generating the model?
Generating the model creates a migration file but does not change the database until you run 'rails db:migrate' which applies the migration and creates the table.
What happens if I forget to specify fields when generating the model?
The model file will be created but the migration will create an empty table with only an id and timestamps, so you need to add fields manually or regenerate.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what file is created at Step 1?
Aconfig/routes.rb
Bdb/migrate/XXXXXXXX_create_articles.rb
Capp/models/article.rb
Dapp/controllers/articles_controller.rb
💡 Hint
Check the 'File Created/Modified' column at Step 1 in the execution table
At which step is the database schema updated?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Result' column for when the database is updated
If you skip editing the migration file, what happens?
ADatabase table will be created with default fields only
BMigration will fail to run
CModel file will not be created
DRails will auto-generate fields based on model code
💡 Hint
Refer to the key moment about missing fields and migration file editing
Concept Snapshot
rails generate model ModelName field:type ...
Creates model file and migration file
Edit migration to customize fields
Run rails db:migrate to update database
Model connects to table named plural of ModelName
Use model in app after migration
Full Transcript
Model generation in Rails starts by running the command 'rails generate model' with the model name and fields. This creates a model file defining the class and a migration file to create the database table. You can edit the migration file to adjust fields. Then you run 'rails db:migrate' to apply the migration and update the database schema. After this, the model is ready to use in your application code.

Practice

(1/5)
1. What does the rails generate model command do in a Rails application?
easy
A. It creates a new model file and a migration file for the database.
B. It runs the database migration to update the schema.
C. It starts the Rails server to test the application.
D. It creates a new controller with views.

Solution

  1. Step 1: Understand the purpose of rails generate model

    This command creates a new model file that defines the data structure and a migration file to set up the database table.
  2. Step 2: Differentiate from other commands

    Running migrations is a separate step, and starting the server or creating controllers are different commands.
  3. Final Answer:

    It creates a new model file and a migration file for the database. -> Option A
  4. Quick Check:

    Model generation = creates model and migration files [OK]
Hint: Model generation creates files, migration applies changes [OK]
Common Mistakes:
  • Confusing model generation with running migrations
  • Thinking it starts the server
  • Mixing up model and controller generation
2. Which of the following is the correct syntax to generate a model named Article with a string field title and a text field content?
easy
A. rails generate model Article title:text content:string
B. rails generate model Article title:string content:text
C. rails generate controller Article title:string content:text
D. rails generate model article title:string content:text

Solution

  1. Step 1: Check the command structure

    The correct command uses 'rails generate model' followed by the model name with capitalized first letter and fields with their types.
  2. Step 2: Verify field types and names

    rails generate model Article title:string content:text correctly uses 'title:string' and 'content:text'. rails generate model Article title:text content:string swaps types incorrectly. rails generate controller Article title:string content:text uses 'controller' instead of 'model'. rails generate model article title:string content:text uses lowercase model name which is incorrect convention.
  3. Final Answer:

    rails generate model Article title:string content:text -> Option B
  4. Quick Check:

    Correct syntax = rails generate model Article title:string content:text [OK]
Hint: Model name capitalized, fields as name:type pairs [OK]
Common Mistakes:
  • Using 'controller' instead of 'model'
  • Swapping field types
  • Using lowercase model name
3. After running rails generate model Product name:string price:decimal and then rails db:migrate, what will be the result when you check the database schema?
medium
A. A products table with columns id, name (string), price (decimal), created_at, and updated_at.
B. A products table with columns id, name (decimal), price (string), created_at, and updated_at.
C. No table created until you manually create it in the database.
D. A products table with only id and timestamps columns.

Solution

  1. Step 1: Understand model generation and migration

    The generate command creates a migration file defining a products table with name as string and price as decimal. Running 'rails db:migrate' applies this to the database.
  2. Step 2: Check expected schema

    The table will have an id primary key, the specified columns with correct types, and timestamps (created_at, updated_at) added by default.
  3. Final Answer:

    A products table with columns id, name (string), price (decimal), created_at, and updated_at. -> Option A
  4. Quick Check:

    Migration creates table with correct columns and timestamps [OK]
Hint: Migration creates table with fields and timestamps [OK]
Common Mistakes:
  • Mixing up field types in the schema
  • Thinking migration doesn't create tables
  • Ignoring default timestamps columns
4. You ran rails generate model User email:string but forgot to run rails db:migrate. What problem will you face if you try to create a new User record?
medium
A. Rails will automatically run the migration for you.
B. The User record will save successfully without errors.
C. ActiveRecord::StatementInvalid error because the users table does not exist.
D. The model file will be missing, causing a LoadError.

Solution

  1. Step 1: Understand migration role

    Generating the model creates files but does not update the database schema until migrations are run.
  2. Step 2: Predict error when saving record

    Without migration, the users table does not exist, so trying to save a User record causes a database error.
  3. Final Answer:

    ActiveRecord::StatementInvalid error because the users table does not exist. -> Option C
  4. Quick Check:

    Missing migration run = database table missing error [OK]
Hint: Always run migrations after generating models [OK]
Common Mistakes:
  • Assuming migration runs automatically
  • Expecting record to save without table
  • Confusing missing model file with migration issue
5. You want to generate a model Order with a status field that can only be 'pending', 'paid', or 'shipped'. Which approach correctly sets this up in Rails?
hard
A. Generate model with status:enum field directly in the generate command.
B. Generate model with status:boolean field to represent the three states.
C. Generate model without status field and add it later manually in the database.
D. Generate model with status:string, then add an enum in the model file for the allowed values.

Solution

  1. Step 1: Understand Rails enum usage

    Rails does not support enum type in migrations directly. Instead, you create a string or integer field and define enum in the model file.
  2. Step 2: Choose correct field type and setup

    Using 'status:string' in the generate command and then adding enum in the model file for 'pending', 'paid', 'shipped' is the correct approach.
  3. Final Answer:

    Generate model with status:string, then add an enum in the model file for the allowed values. -> Option D
  4. Quick Check:

    Enum = string field + model enum definition [OK]
Hint: Use string field plus enum in model, not enum type in migration [OK]
Common Mistakes:
  • Trying to use enum type directly in migration
  • Using boolean for multiple states
  • Skipping field creation in generate command
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard