为 AASM 中的所有转换注册回调?

发布于 2024-08-11 05:34:32 字数 726 浏览 5 评论 0原文

我想在每次状态转换后调用 2 个方法。现在我正在做:

  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_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

显然这不是最好的方法。我正在复制代码,更根本的是,当回调真正应用于整个状态机时,我将回调与特定的转换相关联。有什么更好的方法来处理这个问题?

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_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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里寻她 2024-08-18 05:34:32

为什么不直接使用脏属性来检查保存时状态是否已更改?

就像这样,

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

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
怀里藏娇 2024-08-18 05:34:32

查看 aasm 回调。您想使用 after_all_transitions 方法。

Look aasm callbacks. You want to use after_all_transitions method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文