2013-01-17 56 views
0

如何在Rails 3.x中更新加載關聯數據?Rails:如何更新負載上的關聯數據?

當我加載股票代碼時,如果它們過期,我想更新它的報價。由於ActiveRecord沒有像after_load這樣的回調,所以這樣做的正確方法是什麼?

我的僞代碼看起來像

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 

回答