phil
phil

Reputation: 263

Rails, how to make a database model that records last accessed time

I would like to make a rails model that records last_time_accessed as an attribute. So whenever I access an instance, the current time will be saved. Does anyone know how to do this?

Upvotes: 1

Views: 219

Answers (2)

guitarman
guitarman

Reputation: 3310

You could use an after_find, after_initialize or after_touch module callback. Decide what fits your needs best. But I think it's ugly and be aware, thus you can stress your database with a lot of write requests.

class Model < ActiveRecord::Base
  after_initialize :update_last_time_accessed

  private

  def update_last_time_accessed
    update_attribute(:last_time_accessed, Time.now)
  end
end

Upvotes: 2

Richard Peck
Richard Peck

Reputation: 76774

You'd be best with the after_touch callback:

#app/models/model.rb
class Model < ActiveRecord::Base
  after_touch :set_time

  private

  def set_time
    self.update last_time_accessed: Time.now
  end
end

You'll have to accommodate an extra db request being sent every time you access that model's data.

Upvotes: 1

Related Questions