How can I access the resource that a policy applies to, within the rule?


I’m trying to filter in Ash Policy :read.
How can I access the resource that the policy applies to from the rule?
Is there a way to access the contract in question when this rule runs?
E.g check if ==

defmodule MyApp.Policies.IsContractRecipient do
  use Ash.Policy.FilterCheck

  require Ash.Query
  import Ash.Filter.TemplateHelpers, only: [actor: 1]

  def filter(_options) do
    # Only allow to read contracts where the actor is the recipient
    # Eg. == actor(:email)
    Ash.Query.expr( == ^actor(:email))

Ash.Policy.FilterCheckWithContext — ash v2.18.2 gets the context which also holds the resource.

1 Like

actually, the problem was two fold:

  1. We had used the policy in a contract resource and had prefixed with contract
  2. We hadn’t passed in load option to load client when reading contracts since policy needs preloaded data to be present to pass.

@barnabasJ does FilterCheckWithContext solve issue #2 ?

Filter checks are attached to the query, so in case of a read, it would be part of the where clause if used with AshPostgres. Therefore, you don’t need to explicitly tell Ash to load the data, it will do it itself.