update_attributes无法更新after_save回调中的对象(mongomapper + rails3)

时间:2011-04-26 00:09:25

标签: ruby-on-rails ruby-on-rails-3 mongomapper

我在after_save回调中使用update_attributes更新模型实例时遇到问题。 Update_attributes返回true,但未在模型实例中设置属性。

模型对象Graph有许多Datapoints,我想跟踪最大值和测量时间。由于各种原因,我想对这些信息进行反规范化,所以我得到了以下代码:

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

任何人都能够了解为什么这种更新图表属性的方法会失败?

1 个答案:

答案 0 :(得分:4)

不确定,但实际上我会将其更改为before_savevalidates :max_is_updated

您在示例中使用的方法,即使它正在工作,也会导致对象被保存两次:最初保存一次,update_attributes after_save期间再次保存。