【问题标题】:update_attributes failing to update object in after_save callback (mongomapper+rails3)update_attributes 未能在 after_save 回调中更新对象(mongomapper+rails3)
【发布时间】:2011-04-26 00:09:25
【问题描述】:

我在 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

谁能解释一下为什么这种更新图表属性的方法会失败?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多