繁体   English   中英

在ActiveRecord事务提交之前报告更改。 (Ruby on Rails)

[英]Reporting on changes before the end of an ActiveRecord transaction commits. (Ruby on Rails)

我正在使用ActiveRecord (Rails)在嵌套事务中进行一系列复杂的数据库交互,涉及各种model.update(...)model.where(...).first_or_create(..)

就在交易结束之前,我想报告一下实际发生的更改和即将编写的内容。 大概ActiveRecord保存此信息,但是我无法确定在哪里。

我的代码将类似于( semi-pseudocode

def run options
  begin
  ActiveRecord::Base.transaction do |tranny|
    options[:files].each do |file|
      raw_data = open(file)
      complex_data_stuff raw_data, options
    end
    report
  rescue => e
    "it all went horribly wrong, here's why: #{e.message}"
  end
end

def report tranny
  changes = {}
  tranny.whatschanged?.each do |ch|
    changes[ch.model.class.name] = {} unless changes[ch.model.class.name]
    if changes[ch.model.class.name][ch.kind_of_update]
      changes[ch.model.class.name][ch.kind_of_update] += 1
    else
      changes[ch.model.class.name][ch.kind_of_update] = 1
    end
  end
  changes
end

我将如何实现这样的目标?

http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

这是“脏模型”的最新版本,可跟踪当前对象和已保存版本之间的差异。 您可以像尝试那样通过“更改”方法访问更改。

我在一个项目中添加了一些额外的东西来存储上次更新中发生的更改:它存储在一个实例变量中,因此只能在内存中的特定对象中访问(即,如果重新加载它则看不到它)从数据库中)。

module ActiveRecord
  class Base
    attr_accessor :changed_in_last_save
    before_save :set_changed_in_last_save_hash

    def set_changed_in_last_save_hash
      self.changed_in_last_save_hash = self.changes
    end

    def changed_in_last_save
      self.changed_in_last_save_hash || {}
    end
  end
end

您肯定需要ActiveModel :: Dirty,您可能不需要我的东西,只是提到了它,因为它很相似:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM