ruby-on-railsaasm

AASM: Transitions to a 2 different states depending on conditions


I am using AASM. Is it possible 2 different states depending on conditions For example:

aasm_event :completes do
  transitions :to => condition? ? :complete : :terminate, 
              :from => [:active]
end

the purpose of this is because I'm using legacy code and there are a lot of "completes" calls and the terminate status is new.

I already try override in a new file the state machine as

aasm_event :completes do
  transitions :to => :terminate, 
              :from => [:active]
end

but it didn't work, it still goes to complete state


Solution

  • For this you can set up a guard per transition, which will run before actually running the transition:

    aasm_event :completes do
      transitions :from => [:active], :to => :complete, :guard => :condition?
      transitions :from => [:active], :to => :terminate 
    end
    
    def condition?
      some_contition
    end
    

    This will transition to :complete if :condition? is true, otherwise it will transition to :terminate.