Skip to content

How to work with AASM

thbar edited this page Feb 16, 2012 · 5 revisions

To modify the state of an AASM instance while still going through the transitions, here is what you can do:

class YourModel < ActiveRecord::Base
  # temporary variable used in ActiveAdmin after_save
  attr_accessor :active_admin_requested_event
end
ActiveAdmin.register YourModel do
  after_save do |your_model|
    event = params[:your_model][:active_admin_requested_event]
    unless event.blank?
      # whitelist to ensure we don't run an arbitrary method
      safe_event = (your_model.aasm_events_for_current_state & [event.to_sym]).first
      raise "Forbidden event #{event} requested on instance #{your_model.id}" unless safe_event
      # launch the event with bang
      your_model.send("#{safe_event}!")
    end
  end

  form do |f|
    # your form ...

    # display current status as disabled to avoid modifying it directly
    f.input :status, :input_html => { :disabled => true }, :label => 'Current status'

    # use the attr_accessor to pass the data
    f.input :active_admin_requested_event, :label => 'Change status', :as => :select, :collection => f.object.aasm_events_for_current_state

  end
end
Clone this wiki locally