2011-02-25 84 views
0

刷新結果原來這就是我,這是在型號功能/ product.rbRuby on Rails的:從foo.bars

def get_current_offer_price() 
    if self.prices.blank? 
     p = Price.new() 
     p.product = self 
     p.value = (Amazon.get_price_by_asin(self.code)).to_d/100 
     p.save 
    end 
    self.prices.last.value 
    end 

有趣的是,我第一次運行該系統崩潰,但如果我刷新頁面,並且每隔一段時間,這個工作就完美了。似乎self.prices不是在p.save和下一次調用它之間進行更新,而是稍後將其計算出來。有什麼方法可以在頁面加載完成之前強制刷新?

回答

3
def get_current_offer_price 
    if self.prices.blank? 
     self.prices.create :value => (Amazon.get_price_by_asin(self.code)).to_d/100 
    end 
    self.prices.last.value 
    end 

它通常是一個好主意,用聯想代理創建關聯對象。這可以避免您的問題,這是由關聯代理緩存價格造成的。您創建一個新對象,但緩存的值不會將其提取出來。

使用關聯創建關聯的對象,使緩存失效並使其獲取新的。你也不必手動分配任何主鍵,它只是工作。

0

我會改變你的方法,並使用create方法,像這樣:

def get_current_offer_price() 
    if self.prices.blank? 
     product_id = self.id 
     product_value = (Amazon.get_price_by_asin(self.code)).to_d/100 
     Price.create(:product_id => product_id, :product_value => product_value) 
    end 
    self.prices.last.value 
end