Chapter 12 — Ash: Declarative Domain Modeling
Ecto (Ch 11) gives you explicit building blocks: you write schemas, changesets, context functions, and authorization by hand. Ash raises the abstraction one level: you declare what your resources are and what actions exist on them; the interfaces, validations, authorization, and even API layers are generated from those declarations.
For an Erlang developer this is a familiar trade in new clothes — like moving
from hand-rolled gen_server boilerplate to use GenServer, but applied to
your entire domain model.
12.1 Declarative vs Imperative: Seeing the Difference
The same “register a user” feature, written twice:
Imperative (Ecto + context) — you write how:
defmodule MyApp.Accounts do
alias MyApp.Accounts.{User, Repo}
import Ecto.Changeset
def register(attrs) do
%User{}
|> cast(attrs, [:name, :email])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> unique_constraint(:email)
|> Repo.insert()
end
def get_user!(id), do: Repo.get!(User, id)
def list_users, do: Repo.all(User)
def delete_user(user), do: Repo.delete(user)
end
Declarative (Ash) — you declare what, Ash derives how:
defmodule MyApp.Accounts.User do
use Ash.Resource,
domain: MyApp.Accounts,
data_layer: Ash.DataLayer.Ets # storage is ONE LINE of config (§12.4)
attributes do
uuid_primary_key :id
attribute :name, :string, allow_nil?: false
attribute :email, :ci_string, allow_nil?: false # case-insensitive type!
timestamps()
end
actions do
defaults [:read, :destroy] # standard read/destroy derived for you
create :register do # a NAMED business action, not generic CRUD
accept [:name, :email]
validate attribute_does_not_equal(:name, "admin")
end
end
code_interface do # generates the public functions
define :register, args: [:name, :email]
define :by_id, action: :read, get_by: [:id] # → User.by_id(id), single record
end
end
Usage reads like calling a context function — because it generated one:
MyApp.Accounts.User.register!("Alice", "alice@example.com")
# → %MyApp.Accounts.User{id: "0b8f…", name: "Alice", email: "alice@example.com"}
# get_by actions return a tagged tuple. Non-bang → {:ok, record} or
# {:error, %Ash.Error.Query.NotFound{}}; bang → record, raising when absent.
{:ok, user} = MyApp.Accounts.User.by_id("0b8f…")
user = MyApp.Accounts.User.by_id!("0b8f…")
Not every generated function follows the bang convention: by_id/1 is
generated from get_by:, and its return shape is {:ok, record} or
{:error, %Ash.Error.Query.NotFound{}} rather than a bare record or nil.
That is a deliberate Ash design choice (every
action has an explicit success/error contract), but it is the thing that trips
Ecto developers moving over — Repo.get/2 returns a bare record or nil,
User.by_id/1 does not.
flowchart TD
subgraph IMP["Imperative stack (hand-written per resource)"]
direction TB
H1["changeset function"] --> H2["context functions"] --> H3["authorization checks"] --> H4["API serialization"]
end
subgraph DEC["Ash stack (written once, derived per declaration)"]
direction TB
D1["Resource declarations<br/>attributes · actions · policies"] --> E1["validations"]
D1 --> E2["code interface"]
D1 --> E3["policy enforcement"]
D1 --> E4["JSON:API / GraphQL / forms"]
end
The payoff compounds with scale: every additional resource reuses the machinery; every cross-cutting concern (auth, audit, pagination) is written once in the framework instead of once-per-resource in your contexts.
Naming note: this chapter reuses
MyApp.Accountsfrom Ch 11, where it was a hand-written Ecto context. It is a different design, not an evolution of the same module. Pick one per app — Ash domains and Ecto contexts are alternatives, not layers to stack. (Ch 12 §12.7 covers the legitimate hybrid: Ash for the core domain, raw Ecto queries for analytics.)
12.2 Anatomy of a Resource
Every Ash resource is built from four declaration blocks. Learn these four and you can read any Ash application:
Attributes — what the data looks like
attributes do
uuid_primary_key :id # auto-generated UUID v7 primary key
attribute :title, :string do
allow_nil? false
constraints [max_length: 200] # type-level constraints, validated for you
end
attribute :status, :atom do
constraints [one_of: [:draft, :published, :archived]]
default :draft
end
attribute :view_count, :integer, default: 0
timestamps()
end
Rich built-in types (:ci_string, :date, :decimal, NewType for your
own) replace whole categories of hand-written validators.
Actions — what you can do
Actions are named business operations, not generic CRUD:
actions do
defaults [:read, :destroy]
read :published do
filter expr(status == :published)
pagination keyset?: true, default_limit: 25
end
create :publish_draft do
accept [:title]
change set_attribute(:status, :published)
end
update :increment_views do
accept []
change atomic_update(:view_count, expr(view_count + 1)) # race-free at the DB
end
end
Note what disappeared compared to the imperative version: no manual changeset function, no context wrapper — accept lists, changes, and validations are data about the action, and Ash builds the pipeline from them.
Arguments, Preparations, and Change Modules
Actions accept typed arguments — inputs that need not map to columns:
create :sign_up do
accept [:email]
argument :display_name, :string, allow_nil?: false
change set_attribute(:name, expr(arg(:display_name)))
validate matching(:name, ~r/^[A-Z]/) # args validated too — via the
end # attribute they populate
Read-side shaping goes in prepare — a hook that runs before the data layer:
read :with_comments do
prepare build(load: [:comments], sort: [inserted_at: :desc])
end
When logic outgrows builtins, promote it to a module implementing the
Ash.Resource.Change behaviour — the same move as extracting a plug in
Phoenix:
defmodule MyApp.Changes.Titleize do
use Ash.Resource.Change
@impl true
def change(changeset, _opts, _ctx) do
case Ash.Changeset.fetch_change(changeset, :name) do
{:ok, name} ->
Ash.Changeset.force_change_attribute(
changeset,
:name,
String.capitalize(name)
)
:error ->
changeset
end
end
end
# attach with: change {MyApp.Changes.Titleize}
Error Shapes: Ash Errors vs Changesets
Action failures don’t return changesets — they return error class structs, stable across data layers:
# Actions run through a changeset. Two ways to invoke one:
#
# 1. Ash.create/3 directly — works for any resource, no code_interface needed
User
|> Ash.Changeset.for_create(:register, %{name: "Ada", email: "nope"})
|> Ash.create(domain: MyApp.Accounts)
# 2. the generated code_interface function (from `code_interface` above)
MyApp.Accounts.User.register("Ada", "nope")
case MyApp.Accounts.User.register("Ada", "nope") do
{:ok, user} ->
user
{:error, %Ash.Error.Invalid{errors: errors}} ->
Enum.map(errors, &Exception.message/1)
#=> ["attribute email is invalid"] (rendered human messages)
{:error, %Ash.Error.Forbidden{}} ->
raise "policy denied — see §12.5"
end
| Class | Meaning | Closest Ecto analogue |
|---|---|---|
Invalid | validation/constraint failed | {:error, changeset} |
Forbidden | a policy denied the request | hand-raised in context code |
Framework / Unknown | bugs, storage failures | raised exceptions |
Code that matched on %Ecto.Changeset{} must match on Ash.Error.*
instead; Exception.message/1 flattens the nested errors for display.
Relationships & calculations
relationships do
belongs_to :author, MyApp.Blog.Author
has_many :comments, MyApp.Blog.Comment
end
calculations do
calculate :comment_count, :integer, expr(count(comments))
calculate :summary, :string, expr(fragment("left(?, 80)", body))
end
Calculations are expressions the data layer executes — loaded on demand via
Ash.load!(post, :comment_count), never implicit queries.
Loading is explicit, like Ecto preloads (Ch 11 §11.5), but declarative:
require Ash.Query
[post] =
MyApp.Blog.Post
|> Ash.Query.load([:comment_count, author: [:profile]])
|> Ash.read!(domain: MyApp.Blog)
12.3 Domains: Grouping Resources Behind One Interface
Resources register themselves with a domain module — the boundary other code talks to:
defmodule MyApp.Accounts do
use Ash.Domain,
extensions: []
resources do
resource MyApp.Accounts.User
resource MyApp.Accounts.Token
end
end
Domains do not auto-generate generic create/2 or read/1 functions.
A domain is a registry plus config — otp_app, allowed resources, and the
Ash.Domain callbacks. The functions you call come from either the
resource’s code_interface:
# generated on the RESOURCE, not the domain:
MyApp.Accounts.User.register!("Ada", "ada@x.io")
# or Ash.create/3 / Ash.read!/2 with the domain named explicitly:
User
|> Ash.Changeset.for_create(:register, %{name: "Ada", email: "ada@x.io"})
|> Ash.create!(domain: MyApp.Accounts)
This is Ash’s answer to Phoenix’s context convention (Ch 11 §11.7): one
explicit door per bounded context — except the door is generated, so it
can’t drift out of sync with what resources actually support. Note the
module the functions land on: the resource, since code_interface is a
resource-level block.
12.4 Data Layers: Swap Storage Without Rewriting the Domain
The headline feature for Erlang developers. The resource above declared
data_layer: Ash.DataLayer.Ets. Every declaration-driven behavior works
identically when you switch:
| Data layer | Package | Storage | Use it for |
|---|---|---|---|
Ash.DataLayer.Ets | ash | in-memory ETS tables | tests, prototypes |
AshSqlite.DataLayer | ash_sqlite | SQLite | the useful stepping stone from ETS |
AshPostgres.DataLayer | ash_postgres | PostgreSQL | production durability |
Ash.DataLayer.Mnesia | ash | Mnesia (!) | documented as extremely unoptimized — fine for tests, not throughput |
AshCsv.DataLayer | ash_csv | CSV files | fixtures, tiny tools |
“Works identically” means your declarations do not change — not that every feature is equivalent. Capabilities differ per layer, and the ones that bite:
atomic_update(used by counter-style actions) needs a data layer that implements atomics — the ETS, SQLite and Postgres layers do; not all do.:ci_stringis backed by a realcitextcolumn only on Postgres; ETS stores it in memory asAsh.CiString. Case-insensitive query semantics differ per backend.- Keyset (cursor) pagination is not universally available.
- Filter pushdown and index usage are entirely the backend’s business.
The realistic path is ETS (fast tests, zero setup) → SQLite (real SQL semantics, real migrations, still trivial to run) → Postgres. Jumping straight from ETS to Postgres means your test suite never exercises the query dialect you deploy on.
flowchart LR
RES["MyApp.Accounts.User<br/>declarations unchanged"] --> IFACE["same actions,<br/>policies, interfaces"]
IFACE --> A["ETS<br/>(prototyping)"]
IFACE --> B["Mnesia<br/>(distributed dev)"]
IFACE --> C["Postgres<br/>(production)"]
IFACE --> D["CSV<br/>(fixtures)"]
Switching from prototype to production is literally changing one option plus adding migrations (for Postgres):
use Ash.Resource, domain: MyApp.Accounts, data_layer: AshPostgres.DataLayer
postgres do
table "users"
repo MyApp.Repo
end
Your actions, validations, policies, and code interfaces transfer untouched —
the domain logic never knew where rows lived, much like code that only ever
talked to your mnesia wrapper module.
12.5 Policies: Authorization as Declarations
Authorization lives on the resource, enforced on every action path — whether the caller came from HTTP, LiveView, or a background job:
policies do
policy action_type(:read) do
authorize_if always() # public reads
end
policy action_type(:create) do
forbid_unless actor_present()
end
policy action_type([:update, :destroy]) do
authorize_if relates_to_actor_via(:author) # only the author may edit/delete
end
end
require Ash.Query
MyApp.Accounts.User
|> Ash.Query.filter(email == ^email)
|> Ash.read!(authorize?: true, actor: current_user, domain: MyApp.Accounts)
Ash.Query.filter is itself a macro that takes an expression, so
require Ash.Query plus filter(email == ^email) is enough — the pin
interpolates the runtime value. Wrap an expression in expr/1 (from
Ash.Expr) only when you need to build it as a value, for example storing it
in a variable or passing it to a function that expects an Ash.Expr.
If you have ever written the same “is this user allowed?” check in three controllers and forgotten it in a fourth, this is the cure: the check is declared once, next to the thing being protected.
Reading Policy Logic: Allow, Forbid, Bypass
Policies evaluate top-down with three combinators:
- policy blocks are independent gates: if any authorizes, the request proceeds; if all refuse, it’s forbidden.
- forbid_if / forbid_unless inside a policy short-circuit that gate.
- bypass blocks are checked first; when one applies, remaining policies are skipped entirely.
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always() # admins sail through everything
end
policy action_type(:update) do
forbid_unless actor_present() # anonymous edits: hard no
authorize_if relates_to_actor_via(:author)
end
end
Two families of checks hide under those helpers. Simple checks answer
yes/no about the request itself (is there an actor?). Filter checks like
relates_to_actor_via/1 translate into extra WHERE conditions —
authorization becomes query planning, so a forbidden row simply never loads.
That property is what hand-written controller checks never gave you.
12.6 The Ash Ecosystem
| Package | Gives you |
|---|---|
ash_phoenix | forms & query building wired into Phoenix LiveView |
ash_authentication | registration/sessions/OAuth/magic-links as resources |
ash_postgres | the production-grade data layer + migration generators |
ash_json_api / ash_graphql | full JSON:API / GraphQL endpoints from declarations |
With ash_authentication, adding password sign-in is roughly: add the
extension, run its installer generator, and call the generated
sign_in_with_password action from your LiveView. Compare that to assembling
Comeonin + Plug session plumbing by hand.
12.7 Choosing: Ash vs Ecto + Contexts
Honest framing: Ash uses Ecto under the hood (types, casting). This is not either/or — it’s how much you want generated for you.
flowchart TD
Q{"Is your domain mostly<br/>CRUD over relational data<br/>with light validation?"} -->|yes| ECTO["Ecto + hand-written contexts<br/>(Ch 11)<br/>less framework, full control"]
Q -->|"no — many resources,<br/>shared auth/policies,<br/>API surface needed"| MORE{"Do multiple entry points<br/>(web, GraphQL, jobs)<br/>touch the same rules?"}
MORE -->|"yes"| ASH["Ash — declare once,<br/>enforce everywhere"]
MORE -->|"no"| ECTO2["Either works;<br/>Ash still saves boilerplate<br/>as resource count grows"]
| Signal | Lean toward |
|---|---|
| Few entities, bespoke SQL-heavy logic | Ecto directly |
| Team knows Rails/Django-style productivity | Ash |
| Authorization must be uniform across all paths | Ash (policies) |
| Need JSON:API/GraphQL fast | Ash (extensions generate both) |
| Deeply custom queries, CTEs, window fns | Ecto (or Ash fragments) |
| Prototyping storage-swappable domain models | Ash (ETS/Mnesia layers) |
Both approaches coexist in one application without friction — many teams use Ash for the core domain and raw Ecto queries inside reports/analytics.
When NOT to Reach for Ash
The honest disqualifiers, beyond the table above:
- Three resources and a weekend project — the DSL’s compile-time machinery outweighs the boilerplate it saves.
- Analytics-heavy cores dominated by hand-tuned SQL — Ecto’s query surface sits closer to the metal.
- Team fluency — an Ecto-native team ships faster than an Ash-learning-curve team. The gap closes with experience, but it’s real.
- Tight dependency budgets (embedded releases, audited stacks): Ash pulls a family of packages.
The reverse test: if you catch yourself writing the same context function shapes, authorization plumbing, and serialization glue for the fifth time, that repetition is exactly what Ash prices in.
12.8 Testing Ash Resources: Fast by Construction
The ETS data layer turns the Ch 11 sandbox story inside out: no connection, no transactions to roll back — start a fresh domain per test and its tables are brand new:
There is nothing to boot. A domain is not a supervisor — start_supervised!/1
on it would raise. ETS data layers create their tables at first use, and since
the tables are named global state, a sequential suite is the honest default:
defmodule MyApp.AccountsTest do
use ExUnit.Case, async: false # ETS tables are named, shared state
test "registration rejects reserved names" do
assert {:error, %Ash.Error.Invalid{}} =
MyApp.Accounts.User.register("admin", "admin@example.com")
end
test "registered users are readable" do
MyApp.Accounts.User.register!("Ada", "ada@example.com")
assert [%{name: "Ada"}] =
MyApp.Accounts.User
|> Ash.Query.sort(:inserted_at)
|> Ash.read!(domain: MyApp.Accounts)
end
end
The same suite runs unchanged against Postgres in CI — flip the data layer, generate migrations, and only startup differs:
mix ash_postgres.generate_migrations # write priv/repo/migrations from the resources
mix ash_postgres.migrate # apply them
That pair of commands is the whole cost of leaving ETS. Tests this cheap encourage declaring validation behavior first, then letting policies and actions accumulate around proven examples.
Two features worth knowing exist before you need them:
identities— an Ash-level declaration that uniqueness is identity, which upgrades a duplicate from anInvaliderror to a distinct error class callers can branch on. Better than matching error strings from a constraint.AshPhoenix.Form— a form struct with a changeset underneath, so a LiveView form for a nested resource is oneto_form/2call rather than hand-written assign plumbing.
Explore More
- Ash getting started and the Ash documentation — guides are genuinely excellent
AshPhoenix— Form objects that make nested LiveView forms almost trivialAshAuthentication— full auth stack walkthrough- AshAuthentication deep dive
- Exercise idea: rebuild Ch 11’s
Accountscontext as an Ash resource with ETS first, then flip to SQLite/Postgres — count the lines that changed
Checkpoint
- What does
code_interfacegenerate, and why does that matter for consistency? - How does switching
Ash.DataLayer.EtstoAshPostgres.DataLayeravoid rewriting domain logic? - Where do Ash policies live, and which callers do they cover?
- When would plain Ecto beat Ash?
Answers
- Public functions per declared action (
register!,by_id) — the API surface is derived from declarations, so docs, types, and behavior can’t drift apart. - Actions/validations/policies/interfaces are declarative metadata; only the data-layer option (plus migrations) is storage-specific.
- On the resource itself; they’re enforced on every path — HTTP, LiveView,
Oban worker, script — whenever
authorize?: trueflows through a domain. - Small domains dominated by bespoke SQL, when team expertise is already Ecto-native, or when minimal dependency surface outweighs generated convenience.