What does it mean by db update not guaranteed of AASM hook?

115 views Asked by At

I'm reading AASM docs and trying to decide which hook I'm going to use. On their docs: https://github.com/aasm/aasm#extending-aasm enter image description here What does it mean by # if persist successful, database update not guaranteed here? Can anyone explain the differences between before_success and success hooks? Do I have to call .save if I'm modifying an attribute of the same ActiveRecord object on these hooks? Thanks

1

There are 1 answers

0
spickermann On

Let's assume you have an event run defined on your model that changes the state from stop to running like this.

aasm do
  state :stop, initial: true
  state :running

  event :run do
    transitions from: :stop, to: :running
  end
end

Then calling instance.run would try to change the state to running which would fail if the instance is already in running state. If successful, the state would have been changed on the instance in memory, but would not be saved into the database.

Whereas instance.run! would do the same, but would additionally try to save the changed state into the database. Saving the new state into the database could still fail. For example, when there is a validation failing on the record after the state change or because you updated other attributes on the instance at the same time.

That said: Those callbacks are fired based on the state machine logic, not on the underlying database logic. For example, transition success only means that the state changed successfully on the instance in memory, not necessarily in the database too. When you want to fire a callback after the database update, then use a ActiveRecord after_commit callback instead.