Querying
Mix.install([:ash])
Querying
Data Persistence Home AttributesIn this tutorial you will do basic Query and CRUD operations
But first you need to enable all basic CRUD operations.
Do this by adding the :read, :update and :destroy action to your actions.
Enter your solution
defmodule Tutorial.Profile do
use Ash.Resource,
data_layer: Ash.DataLayer.Ets
actions do
defaults([:create])
end
attributes do
uuid_primary_key(:id)
attribute(:name, :string)
end
end
defmodule Tutorial do
use Ash.Api
resources do
resource(Tutorial.Profile)
end
end
Creating
Add 2 Profiles to the database.
- One with the name “Joe Armstrong”
- One with your name
You can create a Profile by:
-
Creating a Changeset with
Ash.Changeset.for_create(Tutorial.Profile, :create, %{name: "Your Name"}), -
Then giving the changeset to
Tutorial.create!().
Hint: Use a pipeline
Show Solution ```elixir Tutorial.Profile |> Ash.Changeset.for_create(:create, %{name: "The Name"}) |> Tutorial.create!() ```Enter your solution
Reading
Now, read all the generated Profiles.
Call Tutorial.read!/1 with the Tutorial.Profile module.
Enter your solution
Now fetch the “Joe Armstrong” Profile.
You can achieve this by introducing a filter.
First you’ll need to require Ash.Query
Then call Ash.Query.filter(name == "Joe Armstrong") with the Tutorial.Profile.
Put the result into the joe variable. read!/1 returns a list, so make sure to extract the single returned value out of that list.
Enter your solution
You’ll use the joe variable in the next sections.
Updating
Now change Joe Armstrong‘s name to Neil Armstrong.
You can do this by providing the Ash.Changeset.for_update/3 with:
-
the resource you want to change, in this case
joe -
the
:updateatom -
a map of the values you want to change, in this case
%{name: "Neil Armstrong"}
Then apply the changeset by calling Tutorial.update!/1 with the changeset.
Hint: Using a pipeline might be a good idea.
Show Solution ```elixir joe |> Ash.Changeset.for_update(:update, %{name: "Neil Armstrong"}) |> Tutorial.update!() ```Enter your solution
Destroying
Finally, remove joe from the database.
Do this using the Tutorial.destroy!/1 function.
Enter your solution
Data Persistence
Home Attributes