2

I use state machine gem called AASM on rails.

There are an event which has two types of transitions.

Three three types of state

state pending
state past_due
state paid

pending can be changed into paid past_due can be changed into paid

  event :pay do
      transitions from: [:pending, :past_due], to: :paid
  end

So here I'd love to do some action only if past_due goes paid.

Any idea?

Toshi
  • 6,012
  • 8
  • 35
  • 58

3 Answers3

4

One way to do this is to define transitions in two separate statements:

event :pay do
  transitions from: :pending, to: :paid
  transitions from: :past_due, to: :paid, after: :do_your_custom_action
end

See more about callbacks in the docs.

Talha Meh
  • 487
  • 7
  • 20
31piy
  • 23,323
  • 6
  • 47
  • 67
  • Actually, using symbol in `transitions from: :past_due, to: :paid, after: :do_your_custom_action` do not work for me. Method `do_your_custom_action` is not called. – Foton Nov 04 '21 at 08:50
  • Sorry my mistake, I was using `before:` not `after:`. `after:` works with symbol. There is no transition`before:` callback. – Foton Nov 04 '21 at 09:07
0

You can attach the after callback to both the transition and the event.

Since the event is same for both transitions you should attach the callback to the specific transition that is from past_due to paid.

As you are covering both flows in a single transition, first step would be to make a separate transition for this flow and attach the callback to it. As,

transitions :from => :past_due, :to => :paid, :after => your_required_action
Farooq
  • 107
  • 1
  • 11
0

Personally, I pass a block to the after callback

event :pay do
  after do
    # do_something
  end
  transitions from: [:pending, :past_due], to: :paid
end

This way I ensure that do_something will be executed after the event :pay finished.

Another way is attach the callback to a transitions, where the callback will be executed after the transitions is finished.

Please, take a look to the docs and read about callbacks and its order of calling to cover your needs

rogelio
  • 1,541
  • 15
  • 19