Ash FrameworkAF
Ash Framework3y ago
33 replies
lifeofdan

Using args in policies

I'm trying to figure out how to use args in my policy as I've seen in the documentation but all I ever get back is nil. Any help would be appreciated. Here is my code. How does one get the attributes to use in your policies? I see in the docs something like ^arg(:attribute_name) but doing so is not working for me. This is my resource.
defmodule OpenBudget.Budgets.Transaction do
  use Ash.Resource,
    data_layer: AshPostgres.DataLayer,
    authorizers: [Ash.Policy.Authorizer]

  def what_is_it(id) do
    dbg(id)
    false
  end

  relationships do
    belongs_to :bank_account, OpenBudget.Budgets.BankAccount do
      primary_key? true
    end
  end

  policies do
    policy action_type(:create) do
      authorize_if actor_present()
    end

    policy action_type([:read, :update, :destroy]) do
      authorize_if expr(what_is_it(^arg(:title)))
      authorize_if expr(^arg(:bank_account_id) == ^actor(:id))
    end
  end

  attributes do
    uuid_primary_key :id
    attribute :title, :string, allow_nil?: false
    attribute :amount, :decimal, allow_nil?: false, default: 0
    attribute :bank_account_id, :uuid, allow_nil?: false
  end

  actions do
    defaults [:update, :destroy]

    read :read do
      get? true
    end

    create :create_transaction do
      accept [:title, :amount]

      argument :bank_account_id, :uuid do
        allow_nil? false
      end

      change manage_relationship(:bank_account_id, :bank_account, type: :append_and_remove)
    end

    update :update_title do
      require_attributes [:title]
    end
  end

  postgres do
    table "transactions"
    repo OpenBudget.Repo
  end
end
image.png
Was this page helpful?