2

我使用activerecord-import gem在單個查詢中導入多個ActiveRecord文檔。然後,我正在使用保存的文檔ID來初始化相關的關聯並導入它們,等等。如何使用ActiveRecord-import gem初始化PaperTrail版本以執行批量插入?

但是,我需要爲所有保存的文檔擁有PaperTrail gem版本和create事件。

有沒有一些簡單的方法來初始化它們,使可能執行批量插入呢?

注意:AR-導入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

是的,它應該可以批量記錄插入到你的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模型。

+0

我知道這一點。我需要找出不同的東西 - 如何從文件路徑內初始化初始化AR對象的版本。這是一個問題,因爲它們只使用':after_create'回調,當我初始化和執行批量插入時,它會被忽略和無用。儘管如此,我發現這個使用補丁的臨時解決方案。 –

+0

我剛剛更新了我的問題,並將該當前解決方案包含在修補程序中。 –