Associations and Embedded Schemas
Handle relationships between different data models using Ecto associations and embed data directly with embedded schemas.
Linking Your Data Together
In relational databases, data is often spread across multiple tables to avoid redundancy and ensure data integrity. Associations in Ecto help you define how these different pieces of data relate to each other.
Think of a blog: A user can write many posts, and each post belongs to one user. Ecto allows you to model these relationships directly in your Elixir schemas.
- Organize related data logically.
- Simplify querying and data retrieval.
- Maintain data consistency.
One User, Many Posts
The most common relationship is one-to-many. For example, one User can have many Posts, but each Post belongs to only one User.
In Ecto, you define this using has_many on the "one" side (e.g., User) and belongs_to on the "many" side (e.g., Post). The belongs_to macro also tells Ecto to add a foreign key (like user_id) to the Post's database table.
All lessons in this course
- Ecto Schema and Database Migrations
- Repo, Changesets, and Queries
- Associations and Embedded Schemas
- Transactions and Ecto.Multi