2009-04-16 116 views
0

我有一個通過解析數據文件生成的模型。有幾個有趣的值不存在於原始數據文件中,但可以從那些值中派生出來。Rails中模型屬性的懶設置?

但是,這些派生值中的很多值計算起來都很昂貴,所以我想在計算後將它們存儲在數據庫中。

我已經試過這樣:

def profit 
    if not self[:profit] 
    update_attribute :profit, expensive_computation 
    end 
    self[:profit] 
end 

不幸的是,只得到一半的完成任務。計算的值被存儲,但每次我稱爲贏利時,它都會再次計算該值。

UPDATE:

原來,問題是不是在方法,但是在早些時候,一個的find_by_sql聲明瞭Rails的困惑模型的ID的。我結束了與代碼是這樣的:

def profit 
    unless read_attribute(:profit) 
    update_attribute(:profit, expensive_computation) 
    self.save! 
    end 
    read_attribute(:profit) 
end 

回答

2

您創建一個新的方法,並從中刪除讀取邏輯。也許是這樣的

def update_profit 
    update_attribute :profit, expensive_computation 
end 

這樣,你可以分開閱讀邏輯,只是使用的方法來獲得profit Rails所給你。

@model.profit 

哪裏@model是哪裏的代碼應該去的任何階級屬性profit是一個實例。

0

是儘快將取決於當它是可以計算的利潤(例如,作爲記錄首先得到保存,還是有時會遲一些?),以及利潤是否能夠改變。

一般來說它可能是最好把計算在某種before_create/before_save通話,節省了它,只有當它可能被計算和/或改變

vrish88是正確的,你也許應該離開除非你真的需要在需要數據時即時計算這個方法。如果這真的是你需要的,請嘗試:

def profit 
    update_attribute(:profit, expensive_computation) unless read_attribute(:profit) 

    read_attribute(:profit) 
end 
0

這對我來說很好。我的第一個想法是:你在if not self[:profit]行有錯字嗎?

0
def profit 
    super || update_attribute(:profit, expensive_computation) 
    return super 
end 

如果利潤列中有信息,只需調用該對象的原有的盈利方法,它會從數據庫返回profit列的內容。

否則,(即profit柱具有nil的值)使用update_attribute方法來計算profit值,並將其存儲到數據庫中,然後只需再次返回從數據庫中的值。

如果您更希望得到的profit的價值,如果它已經在數據庫或只是true如果昂貴的計算已經運行,只是這樣做(update_attribute返回true或false):

def profit 
    super || update_attribute(:profit, expensive_computation) 
end