Ecto Patterns Reference
Reference for working with Ecto schemas, queries, and migrations.
Iron Laws — Never Violate These
- CHANGESETS ARE FOR EXTERNAL DATA — Use
cast/4 for user/API input, change/2 or put_change/3 for internal trusted data
- NEVER USE
:float FOR MONEY — Always use :decimal or :integer (cents)
- NO RAILS-STYLE POLYMORPHIC ASSOCIATIONS — They break foreign key constraints; use multiple nullable FKs or separate join tables
- ALWAYS PIN VALUES IN QUERIES —
u.name == ^user_input is safe, string interpolation causes SQL injection
- PRELOAD COLLECTIONS, NOT INDIVIDUALS — Preloading in loops = N+1 queries
- CONSTRAINTS BEAT VALIDATIONS FOR RACE CONDITIONS — Validations provide quick feedback, constraints provide DB-level safety
- SEPARATE QUERIES FOR
has_many, JOIN FOR belongs_to — Avoids row multiplication
- NO IMPLICIT CROSS JOINS —
from(a in A, b in B) without on: creates Cartesian product
- DEDUP BEFORE
cast_assoc WITH SHARED DATA — When multiple parents share child data, deduplicate child records BEFORE building changesets. Dedup only works within a single changeset
Quick Schema Template
defmodule MyApp.Context.Entity do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "entities" do
field :name, :string
field :status, Ecto.Enum, values: [:draft, :active, :archived]
field :amount_cents, :integer # Never :float for money!
belongs_to :user, MyApp.Accounts.User
timestamps(type: :utc_datetime_usec)
end
def changeset(entity, attrs) do
entity
|> cast(attrs, [:name, :status, :amount_cents])
|> validate_required([:name])
|> foreign_key_constraint(:user_id)
end
end
Quick Decisions
cast vs put_change vs change
| Function |
Use When |
cast/4 |
External data (user input, API) |
put_change/3 |
Internal trusted data (timestamps, computed) |
change/2 |
Internal data from existing struct |
Preload Strategy
| Relationship |
Strategy |
belongs_to |
JOIN (single query) |
has_many |
Separate queries (avoid row multiplication) |
Common Anti-patterns
| Wrong |
Right |
field :amount, :float |
field :amount_cents, :integer |
"SELECT * WHERE name = '#{name}'" |
from(u in User, where: u.name == ^name) |
Repo.all(User) |> Enum.filter(& &1.active) |
from(u in User, where: u.active) |
| Preloading in loops |
Repo.preload(posts, :comments) |
Repo.get!(User, user_id) with user input |
Repo.get(User, id) + handle nil |
References
For detailed patterns, see:
${CLAUDE_SKILL_DIR}/references/changesets.md - cast vs put_change, custom validations, prepare_changes
${CLAUDE_SKILL_DIR}/references/queries.md - Composable queries, dynamic, subqueries, preloading
${CLAUDE_SKILL_DIR}/references/migrations.md - Safe migrations, concurrent indexes, NOT NULL
${CLAUDE_SKILL_DIR}/references/transactions.md - Repo.transact, Ecto.Multi, upserts
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: ecto-patterns3description: Ecto patterns — schemas, changesets, queries, migrations, Multi, associations, preloads, upserts. Use when editing Repo calls, Ecto.Query, or schema fields. Skip for Ash. Use when this capability is needed.4---56# Ecto Patterns Reference78Reference for working with Ecto schemas, queries, and migrations.910## Iron Laws — Never Violate These11121. **CHANGESETS ARE FOR EXTERNAL DATA** — Use `cast/4` for user/API input, `change/2` or `put_change/3` for internal trusted data132. **NEVER USE `:float` FOR MONEY** — Always use `:decimal` or `:integer` (cents)143. **NO RAILS-STYLE POLYMORPHIC ASSOCIATIONS** — They break foreign key constraints; use multiple nullable FKs or separate join tables154. **ALWAYS PIN VALUES IN QUERIES** — `u.name == ^user_input` is safe, string interpolation causes SQL injection165. **PRELOAD COLLECTIONS, NOT INDIVIDUALS** — Preloading in loops = N+1 queries176. **CONSTRAINTS BEAT VALIDATIONS FOR RACE CONDITIONS** — Validations provide quick feedback, constraints provide DB-level safety187. **SEPARATE QUERIES FOR `has_many`, JOIN FOR `belongs_to`** — Avoids row multiplication198. **NO IMPLICIT CROSS JOINS** — `from(a in A, b in B)` without `on:` creates Cartesian product209. **DEDUP BEFORE `cast_assoc` WITH SHARED DATA** — When multiple parents share child data, deduplicate child records BEFORE building changesets. Dedup only works within a single changeset2122## Quick Schema Template2324```elixir25defmodule MyApp.Context.Entity do26 use Ecto.Schema27 import Ecto.Changeset2829 @primary_key {:id, :binary_id, autogenerate: true}30 @foreign_key_type :binary_id3132 schema "entities" do33 field :name, :string34 field :status, Ecto.Enum, values: [:draft, :active, :archived]35 field :amount_cents, :integer # Never :float for money!36 belongs_to :user, MyApp.Accounts.User37 timestamps(type: :utc_datetime_usec)38 end3940 def changeset(entity, attrs) do41 entity42 |> cast(attrs, [:name, :status, :amount_cents])43 |> validate_required([:name])44 |> foreign_key_constraint(:user_id)45 end46end47```4849## Quick Decisions5051### cast vs put_change vs change5253| Function | Use When |54|----------|----------|55| `cast/4` | External data (user input, API) |56| `put_change/3` | Internal trusted data (timestamps, computed) |57| `change/2` | Internal data from existing struct |5859### Preload Strategy6061| Relationship | Strategy |62|--------------|----------|63| `belongs_to` | JOIN (single query) |64| `has_many` | Separate queries (avoid row multiplication) |6566## Common Anti-patterns6768| Wrong | Right |69|-------|-------|70| `field :amount, :float` | `field :amount_cents, :integer` |71| `"SELECT * WHERE name = '#{name}'"` | `from(u in User, where: u.name == ^name)` |72| `Repo.all(User) \|> Enum.filter(& &1.active)` | `from(u in User, where: u.active)` |73| Preloading in loops | `Repo.preload(posts, :comments)` |74| `Repo.get!(User, user_id)` with user input | `Repo.get(User, id)` + handle nil |7576## References7778For detailed patterns, see:7980- `${CLAUDE_SKILL_DIR}/references/changesets.md` - cast vs put_change, custom validations, prepare_changes81- `${CLAUDE_SKILL_DIR}/references/queries.md` - Composable queries, dynamic, subqueries, preloading82- `${CLAUDE_SKILL_DIR}/references/migrations.md` - Safe migrations, concurrent indexes, NOT NULL83- `${CLAUDE_SKILL_DIR}/references/transactions.md` - Repo.transact, Ecto.Multi, upserts8485---86> Converted and distributed by [TomeVault](https://tomevault.io/claim/oliver-kriska) — claim your Tome and manage your conversions.87<!-- tomevault:4.0:skill_md:2026-04-11 -->