Calculate only on a read action
Hello everyone. Just starting out with Ash and so far, so good. I'm starting to figure a few things out. What I'm currently struggling with is having a
calculate
only run on a read
action.
I have an embedded resource where I'm using a calculate
to generate a URL from another field. Here is a snippet from parent resource where the embedded is loaded:
That works and I get the calculated :url
field injected into the embedded resource when reading items. Yay! My issue is that the :url
field is also being written to the embedded field on create
.
How can I have the calculate run only during the read actions?
I tried using a various Ash.Query
functions in aprepare
in the read action of the embedded resource as well as in the read action of the parent, but couldn't get it load and/or not generate errors.17 Replies
🤔 so when you write, its writing
url
into the database?
But url
is a calculation on the embedded resource?
That sounds like a bug to meYes. It generates the
url
field when creating the parent resource.So how does this manifest? Does the url field not get updated properly later on?
I haven't tried updating yet. I'm just starting out as I mentioned, so I could be doing something wrong.
I'm still not quite sure what the behavior we're trying to avoid is. Is it the fact that the
url
calcualtion is expensive so you don't want it to run on creates?I'm generating the
url
from another field in the embedded with part of the url
(scheme, host, etc.) coming from the application and it might change so I don't want it in the DB.Got it. And you've confirmed that its actually in the database?
I only want the path and I generate the full
url
to send to the client.I think we might just be loading the calculation when you do the create, not necessarily actually storing the value
Yes. It's in the DB.
Got it, that is a bug
calculations should never be stored in the database
thats the whole point of them 😆
Can I see your embedded resource/the calculation?
I tested with data I have in the DB before I tried to create
And on reads, it was generating the
url
field.
I'm testing Ash in a current project thus the Ash
in the module names 🙂
I created the Media.Ash.Objects.CdnUrl
calculation because I'm calling into another module that takes the full_path
and replaces part of it and returns the url
Makes perfect sense 👍
can you try the main branch of ash and see if that resolves your issue?
Sure. I'll give it a try in a bit and let you know.
Thank you Zack!
Oops... Zach... sorry 😦
not a problem 😆 it happens all the time
Hopefully that fixes the issue. I don't know why we were explicitly storing calculations, but I can't think of a good reason that we should be
Okay. The main branch fixed it. Now I will continue on my Ash journey!
Thanks for all your work Zach!
🥳