0

before_update仅当特定字段发生更改时,我的方法才需要更新另一个对象。我们可以访问原始数据还是需要从数据库中加载它?例如:

class Log < ActiveRecord::Base
  attr_accessible :points, :student_id
  belongs_to :student

  before_update :update_points

  private
  def update_points
    if points != original_log.points
      student.points += points - original_log.points
      student.save
    end
  end
end

我需要那个original_log或原来的points。如果我无权访问数据库,我认为在def update_points?下添加它是安全的。

original_log = Log.find(id)
4

1 回答 1

1

我自己从未使用过它,但看起来 ActiveModel 会为您跟踪并提供一种points_was方法。所以以下应该工作:

def update_points
  if points != points_was
    student.points += points - points_was
    student.save
  end
end
于 2012-11-23T10:22:59.870 回答