【问题标题】:Rails before_update callback able to access original data?Rails before_update 回调能够访问原始数据?
【发布时间】:2012-11-23 10:10:56
【问题描述】:

我的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)

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord orm ruby-on-rails-3.2


    【解决方案1】:

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

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

    【讨论】:

    • 正是我想要的,但我找不到关于此的任何文档! _wasActiveRecord 的现代版本中被弃用了吗?我现在正在尝试。
    • 这和我希望的完全一样,我什至可以使用_changed? 方法来代替points != points_was。关于这些肮脏方法的唯一文档位于api.rubyonrails.org/classes/ActiveModel/Dirty.html。它是“一种以与 Active Record 相同的方式跟踪对象更改的方法”。所以它非常简要地描述了_was,我想我们可以假设它也适用于 ActiveRecord 对象。鉴于缺乏关于它已弃用或不支持的文档,我有点担心。
    • ActiveModelActiveRecord::Base中包含的模块之一; Rails 3 将其许多功能拆分为单独的子模块。所以它是最新的并受支持。很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    相关资源
    最近更新 更多