开发者

Rails error handling with AASM state machine

I'm using the rubyist-aasm state machine for handling the different states in my Event object (event initialized, event discussed, event published, etc.). I added guards to prevent state changes when certain conditions aren't met.

This all works fine but it doesn't show any errors when a state change was rejected by the guard. An开发者_开发百科y idea how I can see the state didn't change? I could check the states manually but it sounds like an ugly solution.

aasm_state :firststate 
aasm_state :secondstate  

aasm_event :approve do
  transitions :to => :secondstate, :from => [:firststate], :guard => :has_a_price? 
end

def has_a_price?   
  self.price.present?
end


With SimpleStateMachine you can guard state transitions by adding errors:

def approve
  errors.add(:price, 'Invalid') if price.blank?
end
event :approve, :firststate => :secondstate

Although in this case the price being present isn't related to the event so it would be enough to do:

validates_presence_of :price, :if => "self.second_state?"
event :approve, :firststate => :secondstate


I know in rubyist-aasm 2.0.2 you can call add '!' to the transition method call which will return false if the transition failed. So lets say you have a controller method named approve:

def approve
  @event = Event.find params[:id]

  if @event.approve!
    # transition occurred
  else
    # handle the failed transition (flash or errors)
  end
end

Let me know what you think?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜