我在 after_save 回调中使用 update_attributes 更新模型实例时遇到问题。 Update_attributes 返回 true,但未在模型实例中设置属性。
模型对象 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
谁能解释一下为什么这种更新图表属性的方法会失败?
最佳答案
不确定,但实际上我会将其更改为 before_save
或 validates :max_is_updated
。
您在示例中使用的方法,即使它正在运行,也会导致对象被保存两次:一次是在最初保存时,另一次是在 中的
。update_attributes
期间保存后
关于ruby-on-rails - update_attributes 无法在 after_save 回调中更新对象 (mongomapper+rails3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5784603/