Transactions

There appears to be several ways to handle transactions, but I'd like to really narrow in on a clean way to handle logging entries from within a transaction. Let's use a simple example such as a Post. So when I create a Post from a Phoenix LiveView, I'd like to call a wrapper action for it such as Post.create_with_log(%{title: title}) Then in my Post resource file, I could possibly: 1) Create a code_interface definition such as define(:create, args: [:title], action: :create_with_log) 2) Define the action such as:
actions do
create :create_with_log do
argument(:title, :string)
Post.create!(title: ^arg(:title))
Post.log!(:create, "Created a new post.")
end
end
actions do
create :create_with_log do
argument(:title, :string)
Post.create!(title: ^arg(:title))
Post.log!(:create, "Created a new post.")
end
end
Of course this is simplified not fully working. But it's not clear to me if this is the idiomatic way to handle something like this. I can use Flows or even wrap an Ecto.Multi call, but seems that actions are already transactional and I should be able to re-use the mechanism for this. Thoughts?
3 Replies
rohan
rohan2y ago
you could define a custom change that has an after_action. Then in the action you could do something like: change Log, type: :create, message: "Created new post" probably you could even infer the type from the changeset so you could make it even cleaner before and after actions happen in the transaction itsefl
chriscox
chriscoxOP2y ago
Great thanks! Using after_action works great in this scenario.
barnabasj
barnabasj2y ago
I haven't used it myself but there are also telemetry events emitted that you could hook into. https://hexdocs.pm/ash/monitoring.html

Did you find this page helpful?