简体   繁体   中英

rails active record callback that trigger after values are retrieved from database

Is there an active record callback that would let me set a non-db field right after some db fields have their values being retrieved? I need to do it after the database retrieval because I need the values to compute for the non-db field.

I welcome other ways to do this as well. Specifically, I have a days_ago field that is non-db, then I want to create it only after created_at becomes available, and I have to do this inside the model class.

You should use after_find :

after_find :set_days_ago

def set_days_ago
  self.days_ago = DateTime.now - self.created_at.to_datetime if self.created_at
end

It sounds like you might want a 'lazy-loaded' days_ago field. You should only calculate the days_ago value when you actually need it, by adding a method like this to your model:

def days_ago
  return nil unless created_at?
  @days_ago ||= ... # (calculation involving created_at)
end

The first time you call days_ago , it will calculate the value, and cache the value in the @days_ago variable. The second time you call it, it will return the cached value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM