Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

11 - Phoenix crash course #11: Ecto schemas and migrations

Learn how to use Ecto schemas and migrations to manage database structure in Phoenix applications

By Daniel Bergholz • Aug 19, 2025

Learn how to use Ecto schemas and migrations to manage database structure in Phoenix applications.

What is Ecto?

Ecto is the Elixir/Phoenix equivalent of an ORM—it lets you map Elixir structs to database tables and define database interactions in a functional way.

What is a migration?

A migration is a file describing changes to your database schema (create table, add column, etc.). Teams use migrations to synchronize DB structure across all local/dev/prod environments.

How to generate a schema and migration

  • Use mix phx.gen.schema to create both at once. Syntax:
    mix phx.gen.schema Product products name slug:unique console:enum:pc xbox nintendo playstation
  • This creates:
    • A migration file (in priv/repo/migrations) to create the products table
    • A schema file (in lib/your_app) mapping Elixir structs to the DB table

Referencing other tables

Use references in the generator for relationships (e.g., user_id:references:users).

Applying migrations

  • Run mix ecto.migrate to apply DB changes
  • Use mix ecto.drop && mix ecto.migrate to drop/recreate DB if you need a fresh start

What is a schema?

A schema defines the fields and types for records in your table (mapped to an Elixir struct). Extra fields (inserted_at, updated_at, id) are added automatically by Phoenix with timestamps().

Preview of changesets

Changesets are how you validate/sanitize input data before database writes (handled in a separate video).

Summary

This episode covers generating and managing Ecto schemas/migrations in Phoenix for database-backed apps—defining your data model, evolving your schema, and establishing solid foundations for using Elixir structs with real data.

Related

#phoenix-and-elixir #phoenix-crash-course #daniel-bergholz