使用AASM在初始状态上调用方法

时间:2009-02-10 20:58:59

标签: ruby-on-rails ruby rubygems

使用AASM Gem时,是否可以在输入初始状态时调用方法?我希望在提交评论时调用spam_check方法,但它似乎不起作用。

class Comment < ActiveRecord::Base
  include AASM

  aasm_column :state
  aasm_initial_state :submitted
  aasm_state :submitted, :enter => :spam_check
  aasm_state :approved
  aasm_state :rejected

  aasm_event :ham do
    transitions :to => :approved, :from => [:submitted, :rejected]
  end

  aasm_event :spam do
    transitions :to => :rejected, :from => [:submitted, :approved]
  end

  def spam_check
    # Mark the comment as spam or ham...
  end
end

2 个答案:

答案 0 :(得分:1)

如何使用初始化方法?,它不是自我记录,而是应该有效。

答案 1 :(得分:1)

我的猜测是,由于垃圾邮件检查是在设置初始状态之前进行的,因此您的:spam和:ham转换无法执行,因为:from条件表示状态应为:submit,:拒绝或:批准(但实际上,它是零)。初始状态是在before_validation_on_create回调上设置的,那么尝试这样做呢?

after_validation_on_create :spam_check

aasm_event :spam_check do
  transitions :to => :approved, :from => [:submitted, :rejected], :guard => Proc.new {|c| !c.spam?} 
  transitions :to => :rejected, :from => [:submitted, :approved], :guard => 'spam?'
end

def spam?
  # your spam checking routine
end

这应该在spam_check设置后触发initial_state事件,并将ste状态设置为:approved或:rejected