Learn how to use Ecto schemas and migrations to manage database structure in Phoenix applications
Learn how to use Ecto schemas and migrations to manage database structure in Phoenix applications.
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.
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.
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
priv/repo/migrations
) to create the products
tablelib/your_app
) mapping Elixir structs to the DB tableUse references
in the generator for relationships (e.g., user_id:references:users
).
mix ecto.migrate
to apply DB changesmix ecto.drop && mix ecto.migrate
to drop/recreate DB if you need a fresh startA 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()
.
Changesets are how you validate/sanitize input data before database writes (handled in a separate video).
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.