Rails和state_machine gem,当before_transition失败时,转换为错误状态

时间:2017-01-26 15:53:36

标签: ruby-on-rails ruby state-machine

我正在使用state_machine gem来跟踪对象的状态。我有一个before_transition进程来运行,如果有任何错误,我想将对象的状态设置为“errored”,因此它不再是一个活动对象,我被告知出了问题。下面是一个简化的代码片段,用于演示我要做的事情:

class Status < ActiveRecord::Base
  state_machine :initial => :pending do
    state :pending
    state :processed
    state :errored

    event :process do
      transition :pending => :processed
    end
    event :error do
      transition all => :errored
    end

    before_transition :on => :process, :do => :processing_task
    after_failure :on => :process, :do => :log_error
  end

  def processing_task
    puts "Processing Task Started"
    ...do some processing...
    false  #to force the before_transition task to fail
  end

  def log_error
    puts "Error detected, logging results"
    #LogUtility to store error
    error
  end
end

当我运行status.process时,我会收到以下内容:

BEGIN
Processing Task Started
Error detected, logging results
UPDATE SQL COMMAND, state = 'errored'
ROLLBACK

我尝试禁用交易state_machine :initial => :pending, :use_transactions => false',但这没有任何区别。我觉得在before_transition过程中检测到错误时我应该能够转换errored状态吗?

更新

我试着这样做:

def custom_process
  begin
    process!
  rescue => e
    puts e      #debugging purposes
    #log error
    error       #transition to error state
  end
end

然后我可以打电话给object.custom_process这就完成了我的目标,但我在状态机外面创建了自己的过渡,这对我来说感觉有点奇怪。如果这是唯一的方法,我可以像这样实现它,但希望将所有内容保存在状态机中。

0 个答案:

没有答案