alejorivera
alejorivera

Reputation: 935

Best way to log the time of the moment when an attribute was changed on a record in Rails?

I'm using a state-machine in Rails, and I'd like to log time of the last time the state was changed.

What would be the best way to accomplish this? Thanks!

Upvotes: 0

Views: 167

Answers (1)

eirikir
eirikir

Reputation: 3842

First, I would create an attribute to store the time that the state was last changed (assuming the model name Machine):

rails generate migration AddStateChangedAtToMachines state_changed_at:timestamp
rake db:migrate

Then, I would add a before_save callback to set the timestamp if the value has changed (assuming the attribute name state):

class Machine < ActiveRecord::Base
  before_save :set_state_changed_at

  private
  set_state_changed_at
    state_changed_at = Time.zone.now if state_changed?
  end
end

state_changed? is defined by ActiveRecord::Dirty. It returns true if the attribute state on the object differs from the database value of state. It returns false otherwise. This module defines a variety of instance methods for tracking differences between the object's state and the state of the database record it represents, i.e. what's changed on the object since it was last saved.

Upvotes: 2

Related Questions