How to update associated data on load in Rails 3.x?
When I load a stock symbol, I would like to update its quotes if they are outdated. Since ActiveRecord does not have a callback like after_load, what is the right way to do this?
My pseudo code looks like
class Stock < ActiveRecord::Base
has_many :quotes, :limit => 15, :order => 'date desc'
attr_accessible :symbol
after_load :update_history
#correct code is ( Thanks Dutow)
after_initialize :update_history
def update_history
if (quotes.count > 0)
today = Time.now
get_and_store_history unless (quotes[0].updated_at >= today.beginning_of_day && quotes[0].updated_at <= today.end_of_day)
end
end
def get_and_store_history
#Update quotes
end
end
ActiveRecord has a method called after_initialize, which is a callback like after_load.