Persisting values from relationships at creation time
Hi there!
I'm working on a demo that allows
product
s to be purchased by users. Since prices might change over time, I'd like to put the price of the product at the time of purchase into the order
resource record.
Given a product with the following attributes
and orders defined with
what is the best way to preserve the price
value from the product?
My first try adds a purchase action to the Order
resource:
but this causes me to lose the builtin "not found" error response if the product_id
is invalid.
I also considered an after_action
, but it didn't feel right to force change an attribute:
Solution:Jump to solution
```
change before_action(fn changeset, context ->
product_id = Ash.Changeset.get_attribute(changeset, :product_id)
product = AppName.DomainName.get_product!(product_id, actor: context.actor)
...
6 Replies
oof, I meant
before_action
—not after_action
Solution
That is likely how I'd do it
Got it! I just wasn't sure if there was something obvious I was missing since it seems like a scenario that isn't the most uncommon
Yeah, ideally in the future we will have expression basd attribute setting on creates, which only works on updates i.e
change atomic_update(:amount, expr(product.price))
At some point in the future we'll have change atomc_set(:amount, expr(...))
That sounds awesome! With that not present, I'll proceed with the before_action forced change. Thanks!