我有这个多态模型。
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
正如我所看到的,您可以传递notable_type
== Invoice
是状态机过滤其他notable_type的条件
您可以参考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