Ash FrameworkAF
Ash Framework7mo ago
8 replies
Joan Gavelán

Guidance on Generators

Need to implement a generator for a resource action that makes use of
after_action
hooks (organization > establishment > establishment_user)

This is my chain of actions:

# organization.ex
create :create_organization do
  argument :establishment, :map, allow_nil?: false

  change relate_actor(:owner)

  change after_action(fn changeset, org, context ->
           case Lamashka.Establishments.create_establishment(
                  changeset.arguments.establishment,
                  actor: context.actor,
                  tenant: org,
                  context: %{
                    accessing_from: %{
                      source: __MODULE__,
                      name: :establishments
                    }
                  }
                ) do
             {:ok, _establishment} -> {:ok, org}
             {:error, error} -> {:error, Ash.Error.set_path(error, :establishment)}
           end
         end)
end

# establishment.ex
create :create_establishment do
  change after_action(fn _changeset, est, context ->
           Lamashka.Establishments.add_establishment_user!(
             %{user_id: context.actor.id, role: :admin},
             tenant: est,
             context: %{
               accessing_from: %{
                 source: __MODULE__,
                 name: :establishment_users
               }
             }
           )

           {:ok, est}
         end)
end


# establishment_user.ex
create :add_establishment_user do
  accept [:user_id, :role]
end


This is what I'm trying so far without success

  def org(opts \\ []) do
    changeset_generator(
      Organization,
      :create_organization,
      defaults: [
        name: "Organization",
        establishment: %{
          name: "Establishment",
          address: "Address"
        }
      ],
      overrides: opts,
      actor: opts[:actor]
    )
  end


 Invalid Error
   * Invalid value provided for role: does not exist.
Was this page helpful?