ActiveRecord Models & Migrations
Reviewed & published by Brayan K
ActiveRecord is the part of Ruby on Rails that talks to your database. It's an ORM: it maps Ruby objects to database rows so you can store and query data with plain Ruby instead of SQL.
Part of the free Ruby course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
By the end of this lesson you'll generate a model, write and run migrations, understand the schema, and perform CRUD with create, find, where, update, and destroy.
What You'll Learn in This Lesson
- What ActiveRecord and an ORM are
- Generating a model with rails g model
- Writing and running migrations
- The role of db/schema.rb
- CRUD: create, find, where, update, destroy
- How models map to tables
1️⃣ Models and Migrations
A model is a Ruby class inheriting from ApplicationRecord; it maps to a table automatically. The generator also creates a migration, which you apply with rails db:migrate.
# Generate a model and its migration in one command:
# rails g model Post title:string body:text published:boolean
#
# This creates app/models/post.rb:
class Post < ApplicationRecord
# Inheriting from ApplicationRecord makes Post an ActiveRecord model.
# It automatically maps to the "posts" table — no SQL needed.
end
# It also creates a migration file under db/migrate/.
# Apply it to the database with:
# rails db:migrateThe migration describes the table's columns. Running it builds the table and updates db/schema.rb.
# A migration (db/migrate/..._create_posts.rb) describes the table.
class CreatePosts < ActiveRecord::Migration[7.1]
def change
create_table :posts do |t|
t.string :title # a title column (text)
t.text :body # a longer body column
t.boolean :published # true/false column
t.timestamps # adds created_at and updated_at
end
end
end
# Run it: rails db:migrate
# This updates db/schema.rb to reflect the new posts table.2️⃣ CRUD with ActiveRecord
With a model in place, you store and fetch data using Ruby methods. create inserts, find/where/all read, update changes, and destroy deletes.
# The four CRUD operations with ActiveRecord (in rails console):
# CREATE — build and save in one step.
Post.create(title: "Hello", body: "World", published: true)
# READ — find one, query many, or get all.
post = Post.find(1) # by primary key id
drafts = Post.where(published: false) # all matching rows (a relation)
all = Post.all # every post
# UPDATE — change attributes and save.
post.update(title: "Hello again")
# DELETE — remove the row.
post.destroyYour turn. Fill in the right ActiveRecord method for each task.
# 🎯 YOUR TURN — fill in the right ActiveRecord call.
# 1) Create and save a user named "Ada" in one call:
User.______(name: "Ada") # 👉 TODO: build + save
# 2) Find the user whose id is 3:
User.______(3) # 👉 TODO: by primary key
# 3) Get every user whose admin flag is true:
User.______(admin: true) # 👉 TODO: a filtered query
# ✅ Expected:
# User.create(name: "Ada")
# User.find(3)
# User.where(admin: true)Mini-Challenge: Match the Method
For each goal, name the ActiveRecord method you'd call.
# 🎯 MINI-CHALLENGE: pick the method.
# Match each goal to the ActiveRecord method.
#
# 1. Insert a new saved record -> ______
# 2. Look up one record by its id -> ______
# 3. Get all records matching a condition -> ______
# 4. Permanently remove a record -> ______
#
# ✅ Example answers:
# create
# find
# where
# destroy
# your answers hereCommon Errors (and the fix)
- Forgetting rails db:migrate — A new column won't exist until you run the migration.
- Editing schema.rb by hand — Don't; change the schema through a migration so it stays in sync.
- RecordNotFound from find — find raises if the id is missing; use find_by for a nil-or-record result.
- Singular/odd table names — Models are singular (Post), tables are plural (posts); follow the convention.
- Confusing where and find — where returns a relation (many); find returns one record.
Pro Tips
- 💡 Experiment in the console: rails c is the safest place to learn ActiveRecord.
- 💡 One migration per change: small, focused migrations are easy to roll back.
- 💡 Let the ORM write SQL: reach for raw SQL only when you truly need it.
📋 Quick Reference — ActiveRecord
| Concept | Syntax |
|---|---|
| Generate model | rails g model Post title:string |
| Run migrations | rails db:migrate |
| Create | Post.create(title: "Hi") |
| Read one | Post.find(1) |
| Read many | Post.where(published: true) |
| Update / delete | post.update(...) / post.destroy |
🎉 Lesson Complete!
- ✅ ActiveRecord is Rails' ORM, mapping objects to rows
- ✅ rails g model creates a model and migration
- ✅ rails db:migrate applies schema changes
- ✅ db/schema.rb reflects the current structure
- ✅ CRUD: create, find, where, update, destroy
Practice quiz
What is ActiveRecord?
- A CSS framework
- Rails' ORM that maps Ruby objects to database rows
- A routing macro
- A testing tool
Answer: Rails' ORM that maps Ruby objects to database rows. ActiveRecord is Rails' ORM, mapping classes to tables and objects to rows.
A model named Post conventionally maps to which table?
- post
- Posts
- posts
- tbl_post
Answer: posts. By convention a Post model maps to the plural, lowercase posts table.
Which command generates a model with a migration?
- rails g model Post title:string
- rails new model Post
- rails server Post
- rails routes Post
Answer: rails g model Post title:string. rails g model Post title:string creates the model class and a matching migration.
What is a migration?
- A controller action
- A versioned set of instructions to change the database schema
- A view template
- A route helper
Answer: A versioned set of instructions to change the database schema. A migration is a versioned Ruby script describing changes to the database structure.
Which command applies pending migrations to the database?
- rails db:create
- rails db:rollback
- rails server
- rails db:migrate
Answer: rails db:migrate. rails db:migrate runs pending migrations, updating the schema.
How do you create and save a record in one call?
- Post.all
- Post.create(title: "Hi")
- Post.where(title: "Hi")
- Post.destroy
Answer: Post.create(title: "Hi"). Post.create(...) builds and saves a new record in a single call.
Which method finds a record by its primary key id?
- Post.where(5)
- Post.all(5)
- Post.find(5)
- Post.new(5)
Answer: Post.find(5). Post.find(5) returns the record whose id is 5 (raising if none exists).
What does Post.where(published: true) return?
- A single record
- A relation of all matching records
- The count only
- Nothing
Answer: A relation of all matching records. where returns an ActiveRecord::Relation of every record matching the condition.
Which file reflects the database's current structure?
- db/schema.rb
- config/routes.rb
- app/models/post.rb
- Gemfile
Answer: db/schema.rb. db/schema.rb is the auto-generated snapshot of the current database structure.
How do you update an existing record's attribute?
- post.create(title: "New")
- post.where(title: "New")
- post.find(title: "New")
- post.update(title: "New")
Answer: post.update(title: "New"). post.update(title: "New") changes the attribute and saves it.
Continue this course
- Previous: Views, ERB & Partials
- Next: Associations — has_many, belongs_to, has_many :through and many-to-many
- Quick reference: Ruby cheat sheet
Frequently asked questions
What is ActiveRecord and what does ORM mean?
ActiveRecord is the M in Rails' MVC — its Object-Relational Mapper (ORM). An ORM bridges two worlds: object-oriented Ruby and relational database tables. With ActiveRecord, a class like Post maps to a posts table, an instance maps to a single row, and the object's attributes map to columns. You work with familiar Ruby objects and methods (Post.find, post.title, post.save) instead of writing raw SQL. ActiveRecord generates the SQL for you behind the scenes, so most data access in Rails is just method calls on your models.
What are migrations and why use them?
A migration is a versioned Ruby script that describes a change to the database structure — creating a table, adding a column, adding an index, and so on. Instead of editing the database by hand, you write a migration (often generated for you by rails g model or rails g migration) and run rails db:migrate to apply it. Because migrations are timestamped files kept in db/migrate/, your schema changes live in version control alongside your code, can be applied in order on every machine, and can be rolled back with rails db:rollback. This keeps every developer's and server's database in sync.
What is db/schema.rb?
db/schema.rb is an auto-generated Ruby file that represents the current state of your database structure — every table and column as it exists after all migrations have run. You don't edit it by hand; running rails db:migrate updates it for you. It's useful as a single, readable snapshot of the schema, and Rails can load it directly (rails db:schema:load) to build a fresh database quickly without replaying every migration. Think of migrations as the step-by-step history and schema.rb as the resulting current picture.
What are the basic CRUD methods?
CRUD stands for Create, Read, Update, Delete, and ActiveRecord gives you a method for each. Create: Post.create(title: "Hi") builds and saves a record (or Post.new then post.save). Read: Post.find(id) fetches one by primary key, Post.where(condition) returns all matching rows as a relation, and Post.all returns everything. Update: post.update(title: "New") changes attributes and saves them. Delete: post.destroy removes the row. These few methods cover the vast majority of database work in a Rails app, all without writing SQL yourself.