我使用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)
答案 0 :(得分:0)
是的,应该可以将记录批量插入到versions
表中。
insert into versions
(item_id, item_type, event, created_at)
(1, "User", "create", "2016-02-29"),
(2, "User", "create", "2016-02-29"),
(1, "Widget", "create", "2016-02-29")
因为可以使用纯SQL,所以也可以使用ActiveRecord。请记住,PaperTrail::Version
是常规AR模型。