Makes change respect order

So, let's say I have an update or create action where I want to do a bunch of changes in order before the action runs:
update :my_update do
...

change fn change, _ ->
Ash.Changeset.before_action(changeset, fn changeset ->
IO.puts("change 01")
changeset
end)
end

change fn change, _ ->
Ash.Changeset.before_action(changeset, fn changeset ->
IO.puts("change 02")
changeset
end)
end
end
update :my_update do
...

change fn change, _ ->
Ash.Changeset.before_action(changeset, fn changeset ->
IO.puts("change 01")
changeset
end)
end

change fn change, _ ->
Ash.Changeset.before_action(changeset, fn changeset ->
IO.puts("change 02")
changeset
end)
end
end
What I expected is that the changes would respect the order they are declared inside the action, but actually, in this case, they will run in reverse order, I will see first "change 02" and then "change 01" in the terminal. Why is that? This seems counterintuitive, especially if the second change expects something from the first (ex. loading some calculation).
2 Replies
ZachDaniel
ZachDaniel3y ago
So those changes are actually happening in order. What you're seeing is the behavior of adding a before action hook. When you add a before action, it goes before any other before_action hooks that have been added. If you did your IO.puts() outside of that before_action callback, you would see that effect If you want a before_action hook to go after other before_action hooks added before it, use the append?: true option, after the function. i.e before_action(changeset, fn changeset -> end, append?: true)
Blibs
BlibsOP3y ago
That did the trick, thanks!

Did you find this page helpful?