每次触发事件时如何设置属性值?

时间:2012-12-21 17:38:09

标签: ruby-on-rails ruby implementation state state-machine

我正在使用Ruby on Rails 3.2.9而我只是尝试使用state_machine gem。我有以下声明:

class Article < ActiveRecord::Base
  state_machine :attribute => :status, :initial => :unconfirmed do
    state :confirmed, :value => 'confirmed'
    state :unconfirmed, :value => 'unconfirmed'

    event :confirm do
      transition :unconfirmed => :confirmed
    end

    event :unconfirm do
      transition :confirmed => :unconfirmed
    end
  end
end

我还有confirmed_at模型的Article属性,旨在保留:status切换到:confirmed时的最后一次。

如何将confirmed_at属性初始化为当前时间?每次confirmed_at事件被触发时我如何设置:confirm当前时间?

1 个答案:

答案 0 :(得分:0)

看起来这就是before_transition的用途。

before_transition :confirmed => any - :confirmed, :do => :set_confirmed_at

然后按该名称添加方法:

def set_confirmed_at
  self.confirmed_at = Time.now
end