Rails 新手和学习如何使用 state machines.怎么让一个 Actor 的粉丝从哭状态变成哭状态?
class Actor < ApplicationRecord
include AASM
has_many :fans
aasm do
state :laughing, :initial => true
state :crying
event :cry do
transitions :from => :laughing, :to => :crying
end
event :laugh do
transitions :from => :crying, :to => :laughing
end
end
end
class Fan < ApplicationRecord
include AASM
belongs_to :author
aasm do
state :laughing, :initial => true
state :crying
event :cry do
transitions :from => :laughing, :to => :crying
end
event :laugh do
transitions :from => :crying, :to => :laughing
end
end
end
最佳答案
您可以使用 lifecycle callbacks在 actor 上触发更多方法:
class Actor < ApplicationRecord
include AASM
has_many :fans
aasm do
state :laughing, :initial => true
state :crying, :success => :fans_cry_too
# ...
end
private
def fans_cry_too
fans.each(&:cry)
end
end
关于ruby-on-rails - 从另一个模型触发模型中的状态更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49526034/