Reputation: 263
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
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
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