我正在使用activerecord-import gem在单个查询中导入多个 ActiveRecord 文档。然后我使用保存的文档 ID 初始化相关关联并导入它们,等等。
但是,我需要为所有保存的文档提供带有事件的PaperTrail gem版本。create
是否有一些直接的方法来初始化它们以使执行批量插入成为可能?
注意:AR-Import gem 忽略所有回调,所以我在导入后手动处理它们。
谢谢!
UPD-20/05/17:
目前我已经用PaperTrail::Model
. 这是我的.../initializers/paper_trail.rb
:
module PaperTrail
class Version < ActiveRecord::Base
...
end
module ModelPatch
extend ActiveSupport::Concern
included do
# new method added to PaperTrail::Model module to make possible initialize
# `create` versions right after importing resources.
# This method contains modified code from private PaperTrail::Model::InstanceMethods#record_create
# Difference:
# - instead of `create!` we use `new` but with validation and raise exception if it's invalid.
# This is for reinsurance that if something changes after update PaperTrail gem in future
# everything still works or need to fix it.
def initialize_record_create_version
return nil unless paper_trail_switched_on?
data = {
event: paper_trail_event || 'create',
whodunnit: PaperTrail.whodunnit
}
if changed_notably? && self.class.paper_trail_version_class.column_names.include?('object_changes')
data[:object_changes] = if self.class.paper_trail_version_class.object_changes_col_is_json?
changes_for_paper_trail
else
PaperTrail.serializer.dump(changes_for_paper_trail)
end
end
new_v = send(self.class.versions_association_name).new merge_metadata(data)
new_v.valid? ? new_v : fail("Invalid PaperTrail Version: #{new_v.errors&.messages}")
end
end
end
end
PaperTrail::Model.send(:include, PaperTrail::ModelPatch)
UPD-28/01/21:
使用 PaperTrail v10.xx 可以这样工作:
def initialize_record_create_version
return nil unless paper_trail.enabled?
event = Events::Create.new(self, false)
data = event.data.merge!(paper_trail.data_for_create)
new_v = send(self.class.versions_association_name).new data
new_v.valid? ? new_v : fail("Invalid PaperTrail Version: #{new_v.errors&.messages}")
end