开发者

Register callback for all transitions in AASM?

There are 2 methods I want to call after every state transition. Right now I'm doing:

  aasm_event :nominate_for_publishing, :before => [:set_state_last_updated_by, :set_state_updated_at] do
    transitions :to => :under_review, :from => [:work_in_progress]
  end

  aasm_event :publish, :before => [:set_state_last开发者_如何学Python_updated_by, :set_state_updated_at] do
    transitions :to => :published, :from => [:work_in_progress, :under_review], :guard => :is_publishable?
  end

  aasm_event :unpublish, :before => [:set_state_last_updated_by, :set_state_updated_at] do
    transitions :to => :work_in_progress, :from => [:published, :under_review]
  end

Obviously this isn't the best approach. I'm duplicating code, and more fundamentally, I'm associating callbacks with specific transitions when they really apply to the state machine as a whole. What's a better way to handle this?


Why not just use dirty attributes to check if the state has been changed on save?

Like so,

class Model > ActiveRecord::Base

  before_save :set_state_updates

  private

  def set_state_updates
    if state_changed?
      set_state_last_updated_by
      set_state_updated_at
    end
  end 

end


Look aasm callbacks. You want to use after_all_transitions method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜