使用多态状态机进行跟踪

问题描述 投票:0回答:2

我有这个多态模型。

class Note < ApplicationRecord

  belongs_to :notable, polymorphic: true, optional: false


  state_machine :status, initial: :pending do
    transition pending: :approved, on: %i[approve]
    transition pending: :cancelled, on: %i[cancel]
  end
end

和其他两个模型

class Invoice < ApplicationRecord

  has_many :notes, as: :notable, dependent: :destroy
end

class Person < ApplicationRecord

  has_many :notes, as: :notable, dependent: :destroy
end

如您所见,我将便笺以两种方式附加在其个人或发票上。并使用状态机场景是我只想在invoice中使用状态机?这可能吗。所以。如果我的notable_type是“发票”。我的状态为“待处理”,否则为“我的人状态:nil

ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5 state-machine
2个回答
1
投票

正如我所看到的,您可以传递notable_type == Invoice是状态机过滤其他notable_type的条件


0
投票

您可以参考AASM gem。https://github.com/aasm/aasm。这不仅可以帮助您在所有转换中添加防护方法,而且还可以在回调之前和之后。

您还可以添加AASM挂钩方法并在那里设置状态。例如:-

class Note < ApplicationRecord belongs_to :notable, polymorphic: true, optional: false include AASM aasm do state :pending state :approved state :cancelled event :approve do transitions from: :pending, to: :approved, before: some_method, after: some_method1 end event :cancel do transitions from: :pending, to: :cancelled, before: some_method2, after: some_method3 end end def aasm_ensure_initial_state if notable_type == "Invoice" self.aasm_state = :pending else self.aasm_state = nil end end end end

© www.soinside.com 2019 - 2024. All rights reserved.