Working with Transactions
Hello!
I'm working on converting the following Elixir/Ecto function into an Ash action:
This function performs two operations within a transaction:
Creates a new Team with the provided attributes.
Creates a new TeamMember associated with the newly created team and assigns the "admin" role to the specified user.
Here's my current Team resource definition in Ash:
I'm looking for guidance on how to implement the :create_team action in Ash to replicate the behavior of the original Ecto.Multi function. Specifically, I want to ensure that both the team creation and the associated team member creation occur within the same transaction.
Solution:Jump to solution
```elixir
change fn changeset, context ->
Ash.Changeset.after_action(changeset, fn changeset, team ->
team_member_attrs = %{
# actor is in the context...
7 Replies
So a guide to answer this is up next on my list, but in the meantime, what you are looking for in Ash is lifecycle hooks
after_action hooks happen in the same transaction 🙂
Great, this is the way to go. One question though, how to access the actor data?
Solution
This is how I got it working:
I think this can be optimized a little bit. Is there a way to use the tenant id to relate it to the resource being created, something similar to
relate_actor/2
?
This is my TeamMember
resource
In the same way, is there something similar to relates_to_actor_via/2
but for tenants that I can use in my policies? Currently I just have authorize_if always()
as you can seeWhat is the difference between
and
The first one is a shortcut for the second
I usually show the longer one so people understand what's happening
Turns out I don't need to specify the "team_id" team member attribute when I'm already passing in a tenant. It takes the tenant's value and assigns it automatically
I am using this small protocol implementation in my tenant
Team
resource by the way. In case anyone gets confused as to why I am passing the whole tenant this time.
I am using the attribute strategy so I just need to convert the passed tenant into an id. More info about this protocol:
https://hexdocs.pm/ash/multitenancy.html#possible-values-for-tenant