Files
livebook/ash_tutorial/resources.livemd
2025-09-29 19:25:33 +08:00

80 lines
2.8 KiB
Markdown

# Ash: 1 - Resources
```elixir
Application.put_env(:ash, :validate_domain_resource_inclusion?, false)
Application.put_env(:ash, :validate_domain_config_inclusion?, false)
Mix.install([{:ash, "~> 3.0"}], consolidate_protocols: false)
```
## What is a resource?
<div class="flex items-center w-full flex-start justify-between rounded-xl p-4" style="background-color: #f0f5f9; color: #61758a;">
<div class="flex">
<i class="ri-home-fill"></i>
<a class="flex ml-2" style="color: #61758a;" href="overview.livemd">Home</a>
</div>
<div class="flex">
<a class="flex mr-2" style="color: #61758a;" href="actions.livemd">Actions</a>
<i class="ri-arrow-right-fill"></i>
</div>
</div>
<!-- livebook:{"break_markdown":true} -->
The fundamental building blocks of Ash are resources, actions, and domains. The resource is Ash's central concept, so we need to define it well for anything else to make sense, so let's turn to the [Ash Glossary](https://hexdocs.pm/ash/glossary.html#resource).
> The central concept in Ash, a resource is a domain model object in your system, the nouns that your app revolves around. Resources contain definitions of the data they hold in the form of attributes, but also define actions that can be taken on that data and actors that are allowed to run them.
>
> It is not a strict requirement that resources contain data - they can be used purely to create a standard interface for performing tasks - but in practice, most resources will be used to manage data.
A domain simply groups together related resources. Some things can be defined in a domain instead of a resource. We will do this when we get to code interfaces later on.
## Example Code
Here we have a minimal resource called `Profile` that has, aside from its primary key, a single string attribute `name`.
```elixir
defmodule Tutorial.Profile do
use Ash.Resource,
domain: Tutorial
attributes do
uuid_primary_key :id
attribute :name, :string
end
end
```
To be able to do anything with this resource, we also need a domain.
```elixir
defmodule Tutorial do
use Ash.Domain
resources do
resource Tutorial.Profile
end
end
```
Now we can create a changeset for the resource.
```elixir
Tutorial.Profile
|> Ash.Changeset.new()
|> Ash.Changeset.change_attributes(%{name: "John Doe"})
```
Changesets are used to create and update data in Ash. (**Note:** without a data layer, you won't be able to persist creations and changes. This will be shown in a later tutorial.)
<div class="flex items-center w-full flex-start justify-between rounded-xl p-4" style="background-color: #f0f5f9; color: #61758a;">
<div class="flex">
<i class="ri-home-fill"></i>
<a class="flex ml-2" style="color: #61758a;" href="overview.livemd">Home</a>
</div>
<div class="flex">
<a class="flex mr-2" style="color: #61758a;" href="actions.livemd">Actions</a>
<i class="ri-arrow-right-fill"></i>
</div>
</div>