Ash FrameworkAF
Ash Framework3y ago
36 replies
\ ឵឵឵

Policy for explicitly setting relationship on create

I have a number of resources that are is_a other resources. That is:
  defmacro is_a(attr, type, opts \\ []) do
    quote do
      relationships do
        belongs_to unquote(attr), unquote(type) do
          source_attribute unquote(opts[:source_attribute] || :id)
          primary_key? true
          allow_nil? false
        end
      end

      # this part is not in yet
      changes do
        change MaybeCreateParent, on: [:create]
        # TODO
      end
    end
  end

When these resources are created, they optionally accept an:
actions do
  create :create do
    argument :parent, App.Parent
    # ...
  end
end

I'd like to do two things:

1. Be able to roll the automatic creation of the parent into something like above. Can I pass change an MFA?
defmodule MaybeCreateParent do
  def change(cs, _, _) do
    parent = Changeset.get_argument(cs, :parent) || %{}

    cs
    |> Changeset.delete_argument(:parent)
    |> Changeset.manage_relationship(:parent, parent, type: :create)
  end
end


2. Be able to create policies that determine when one is allowed to explicitly set the parent while creating. For example, to specify only users with certain roles should be allowed to explicitly set the parent. Something like:
  policies do
    policy [action_type(:create), changing_relationship(:parent)] do
      authorize_if IsSomeRole
      authorize_if IsAnotherRole
      deny_unless never()
    end
  end
Was this page helpful?