从另一个模型触发模型中的状态更改

时间:2018-03-28 04:19:32

标签: ruby-on-rails ruby

铁杆新手并学习如何使用state machines.我如何让一个状态正在哭泣的演员的粉丝变成同样的哭泣状态?

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

1 个答案:

答案 0 :(得分:3)

您可以使用lifecycle callbacks触发演员的其他方法:

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