Anonymous Function Queries (Preparations)

I can't seem to get the syntax right, what am I doing wrong?
preparations do
prepare fn query, context ->
case query.tenant do
%MyApp.Orgs.Org{id: id} ->
query
|> Ash.Query.filter(org_id == ^id)

_ ->
query
end
end
end
preparations do
prepare fn query, context ->
case query.tenant do
%MyApp.Orgs.Org{id: id} ->
query
|> Ash.Query.filter(org_id == ^id)

_ ->
query
end
end
end
It yells at me for the org_id var and use of the pin operator. I tried without (org_id: id) and got a different error.
2 Replies
Songyun
SongyunOP•8h ago
I got this working in a separate module. I don't understand why it doesn't work in an anon. func with a resource's global preparations, though.
defmodule MyApp.Preparations.ScopeToTenant do
use Ash.Resource.Preparation

@impl true
def prepare(query, _opts, context) do
case context.tenant do
nil ->
query

%CombatLog.Orgs.Org{id: id} ->
query
|> Ash.Query.filter(org_id == ^id)
end
end
end
defmodule MyApp.Preparations.ScopeToTenant do
use Ash.Resource.Preparation

@impl true
def prepare(query, _opts, context) do
case context.tenant do
nil ->
query

%CombatLog.Orgs.Org{id: id} ->
query
|> Ash.Query.filter(org_id == ^id)
end
end
end
Would also appreciate an explanation for why nil checks are necessary in these if anyone knows.
ZachDaniel
ZachDaniel•7h ago
🤔 I thought we fixed that, but in preparations, Ash.Query is required automatically I thought that was the case for resources too, but perhaps not Yeah, it should be requiring Ash.Query AFAICT are you on a recent version of Ash?

Did you find this page helpful?