Autoload an aggregation, relationship or calculation in a read action

I have a read action where I want to return the data with some aggregation/relationship/calculation data already computed instead of returning #Ash.NotLoaded<> in these fields and having to manually run the load function to load them. I can't find in the documentation how to do that
3 Replies
ZachDaniel
ZachDaniel3y ago
You can use a “preparation” which is like a change but for read actions. If you always want it to be loaded you can use the top level preparations block which runs on all reads
preparations do
prepare build(load: [:calc])
end
preparations do
prepare build(load: [:calc])
end
That loads the calculation on all queries.
Blibs
BlibsOP3y ago
Ah! That makes sense. I was trying that, but I thought I had to replace the build with load loke this prepare load(:last_bid_price) 😅 Thanks, now it works great Is there something similar for create and update actions? I would like to create the resource and already have these loaded too
ZachDaniel
ZachDaniel3y ago
Yep! You can add a global change I believe there is a load/1 built in change. But if not you can use a global change + returning a changeset with an after action hook using Ash.Changeset.after_action/2

Did you find this page helpful?