Need to return `nil` for a belongs_to relationship value based on criteria

I’m building an AshGraphql query that should return null for a belongs_to field if the actor doesn’t have permission to access that field, rather that raising a policy violation from the child resource. Right now, there is a policy violation when there is a read attempt on the belongs_to field. This actually isn’t the behavior I need. I need to the field to simply be nil if the user doesn’t have the right privileges.

I tried the the filter option to belongs_to, but it doesn’t appear to prevent reading the related field, even if the expression is expr(false). The policy violation on the related resource is still triggered, failing the parent read.

defmodule GF.Events.Event2 do
  # ...

  relationships do
    belongs_to :venue, GF.Events.Venue2 do
      attribute_type :integer
      public? true
      # Want to restrict access based on actor criteria, but even a `false` expression doesn't prevent a read to Venue2
      filter expr(false)
    end
  end
end

How can I have the belongs_to value be nil for certain criteria when the child record actually exists, without raising a policy violation on the child resource/

1 Like

So this is something that we don’t actually have at the moment. When requesting related data currently the value is either provided or the entire request is forbidden. However, this is a feature that we can add at the framework level likely without too much fuss. We’d have to make it configurable, perhaps globally, perhaps on a relationship-by-relationship basis. This would also change the types of to_many relationships because they could return a list or nil (plus errors).

In the meantime what you could do is write a calculation, and then use field policies on that calculation.

1 Like

That makes sense. I’ll do a calculation, which is already being done for several other fields on this resource. Thanks!

1 Like