2011-04-26 21 views
3

我在after_save回調中更新模型實例時使用update_attributes時遇到問題。 Update_attributes返回true,但屬性沒有在模型實例中設置。update_attributes無法更新after_save回調中的對象(mongomapper + rails3)

模型對象Graph有許多數據點,我想跟蹤最大值以及何時測量。由於各種原因,我想這種非規範化的信息,所以我有下面的代碼:

class Graph 
    include MongoMapper::Document 
    many :datapoints, :dependent=>:destroy 

    key :max_value, Float 
    key :max_value_at, Time 
end 

,並在我的數據點:

class Datapoint 
    belongs_to :graph 

    key :graph_id, ObjectId, :required=>true 
    key :value, Float 
    key :time, Time 

    after_save :update_max_on_save 

    .... 

    def update_max_on_save 
    g = self.graph? ? self.graph : Graph.find_by_id(self.graph_id) 
    if g.max_value.nil? || g.max_value < self.value 
     g.update_attributes({:max_value=>self.value, :max_value_at=>self.time}) 
    end 
    end 
end 

任何人都能夠揭示爲什麼這種方法更新一些光圖的屬性會失敗?

回答

4

不確定,但我實際上將其更改爲before_savevalidates :max_is_updated

在示例中使用的方法(即使它正在工作)會導致該對象被保存兩次:一次是最初保存的對象,另一次是update_attributesafter_save

相關問題