Ash FrameworkAF
Ash Framework8mo ago
31 replies
⿻ eileen

`change manage_relationship(...type: :remove)` not working

I have a
many_to_many
relationship between Organization and SubscriptionPlan. The Organization has the following two actions:

    update :subscribe do
      argument :plan, :struct, constraints: [instance_of: SubscriptionPlan]
      accept []
      require_atomic? false
      change manage_relationship(:plan, :subscription_plans, type: :append)
    end

    update :unsubscribe do
      argument :plan, :struct, constraints: [instance_of: SubscriptionPlan]
      accept []
      require_atomic? false
      change manage_relationship(:plan, :subscription_plans, type: :remove)
    end


The :subscribe action seems to work fine. But the :unsubscribe action fails with the following :invalid error:

[%Ash.Error.Changes.InvalidRelationship{relationship: :subscription_plans, message: "changes would create a new related record", splode: Ash.Error, bread_crumbs: ["Error returned from: MyApp.Accounts.Organization.unsubscribe"]


I'm a little baffled by this one. Also, if I change the
manage_relationship
options from type: :remove to the following:

[
  on_no_match: :ignore,
  on_match: :unrelate,
  on_missing: :ignore
]  

(this basically just changes on_no_match from :error to :ignore)

... my test also fails. It seems to remove the subscription from the Organization but not the SubscriptionPlan:

plan = plan |> Ash.load!([:subscribers], actor: user) |> dbg
assert plan.subscribers |> length == 0


Not sure what I'm doing wrong here 🤔
Solution
So the mistake I was making was in my accessing_through policy:

    policy accessing_from(MyApp.Accounts.Organization, :subscribers) do
      authorize_if always()
    end


I thought that second parameter was supposed to refer to the relationship defined on the resource that was defining the policy, but it's actually the relationship defined on the resource being referenced in the policy.
Was this page helpful?