Filtering inside a load

Hopefully an easy one. I have a code interface that I'm calling inside a calculation module like this:
defp calculate_least_engaged(organization, after_datetime, before_datetime) do
descendant_orgs = Organization.get_descendant_organizations!([organization.id], load: [users: [:first_name, :last_name]])
...
end
defp calculate_least_engaged(organization, after_datetime, before_datetime) do
descendant_orgs = Organization.get_descendant_organizations!([organization.id], load: [users: [:first_name, :last_name]])
...
end
Assuming I pass a graduation_year argument to the calculation (and access it as the fourth param on the function), how can I filter the users that are being loaded?
3 Replies
barnabasj
barnabasj4mo ago
You can also supply a inital query for the load
require Ash.Query

defp calculate_least_engaged(organization, after_datetime, before_datetime) do
query =
User
|> Ash.Query.select([:first_name, :last_name])
|> Ash.Query.filter(graduation_year == ^Ash.Changeset.get_argument(changeset, :graduation_year)


descendant_orgs = Organization.get_descendant_organizations!([organization.id], load: [users: query])
...
end
require Ash.Query

defp calculate_least_engaged(organization, after_datetime, before_datetime) do
query =
User
|> Ash.Query.select([:first_name, :last_name])
|> Ash.Query.filter(graduation_year == ^Ash.Changeset.get_argument(changeset, :graduation_year)


descendant_orgs = Organization.get_descendant_organizations!([organization.id], load: [users: query])
...
end
Ege
EgeOP4mo ago
where is changeset coming from?
barnabasj
barnabasj4mo ago
ah sorry, I mixed up changes and calculations it should be
require Ash.Query

defp calculate_least_engaged(organization, after_datetime, before_datetime) do
query =
User
|> Ash.Query.select([:first_name, :last_name])
|> Ash.Query.filter(graduation_year == ^context.arguments.graduation_year)


descendant_orgs = Organization.get_descendant_organizations!([organization.id], load: [users: query])
...
end
require Ash.Query

defp calculate_least_engaged(organization, after_datetime, before_datetime) do
query =
User
|> Ash.Query.select([:first_name, :last_name])
|> Ash.Query.filter(graduation_year == ^context.arguments.graduation_year)


descendant_orgs = Organization.get_descendant_organizations!([organization.id], load: [users: query])
...
end
context should be the 3. argument to the calculate function your are calling this private function from

Did you find this page helpful?