Skip to content

State transitions with guard clauses that require arguments

Pooja Mane edited this page Jun 22, 2017 · 4 revisions

Here is an example ActiveRecord class that defines guard methods that require arguments:

class Foo < ApplicationRecord
  include AASM

  aasm do
    state :inactive, initial: true
    state :pending_approval, :approved

    event :send_for_approval do
      transitions from: :inactive, to: :pending_approval, :guard => :approver?
    end

    event :approve do
      transitions from: :pending_approval, to: :approved, :guard => :member?
    end
  end

  def approver?(user)
    user.approver?
  end

  def member?(user)
    user.member?
  end
end

Here is how you invoke the state transitions:

foo = Foo.new

approver = User.new(approver: true)
foo.send_for_approval!(approver)

member = User.new(member: true)
foo.approve!(member)

# show permitted states with guard parameter
foo.aasm.states({:permitted => true}, member).map(&:name)