Ash: 12 - Calculations
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)
Calculations
Aggregates HomeDomainCalculations in Ash allow for displaying complex values as a top level value of a resource.
Create a full_name
calculation on the User resource.
You already have the first_name
and last_name
defined, you can get the full_name
by concatenating them with a space in the middle.
First, add a calculations do ... end
block.
Then inside this block, add calculate :full_name, :string, expr(first_name <> " " <> last_name)
Show Solution
calculations do
calculate :full_name, :string, expr(first_name <> " " <> last_name)
end
Enter your solution
defmodule Tutorial.Accounts.User do
use Ash.Resource,
domain: Tutorial.Accounts,
data_layer: Ash.DataLayer.Ets
actions do
defaults([:read])
create :create do
accept([:first_name, :last_name])
end
end
attributes do
uuid_primary_key(:id)
attribute(:first_name, :string, allow_nil?: false)
attribute(:last_name, :string, allow_nil?: false)
end
# <--- Add the calculations here
calculations do
calculate :full_name, :string, expr(first_name <> " " <> last_name)
end
end
defmodule Tutorial.Accounts do
use Ash.Domain
resources do
resource(Tutorial.Accounts.User)
end
end
Create a User
Create a User and load in the full_name
Tutorial.Accounts.User
|> Ash.Changeset.for_create(:create, %{first_name: "Joe", last_name: "Armstrong"})
|> Ash.create!()
|> Ash.load!([:full_name])
This is the most basic example of a calculation. Note that calculations allow you to do any arbitrary operation on the Resource. More on this inside the documentation.
Aggregates HomeDomain