本文介绍了Papertrail和载波的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型同时使用:Carrierwave用于存储照片,而PaperTrail用于版本控制.

I have a model that use both: Carrierwave for store photos, and PaperTrail for versioning.

我还用config.remove_previously_stored_files_after_update = false

问题是PaperTrail尝试存储照片(CarrierWave Uploader)中的整个Ruby对象,而不是简单地存储一个字符串(即其网址)

The problem is that PaperTrail try to store the whole Ruby Object from the photo (CarrierWave Uploader) instead of simply a string (that would be its url)

(版本表,列对象)

---
first_name: Foo
last_name: Bar
photo: !ruby/object:PhotoUploader
  model: !ruby/object:Bla
    attributes:
      id: 2
      first_name: Foo1
      segundo_nombre: 'Bar1'
      ........

如何解决此问题,以便在照片版本中存储简单的字符串?

How can I fix this to store a simple string in the photo version?

推荐答案

您可以在版本控制的模型上覆盖item_before_change,这样您就不必直接调用上载器accesor而是使用write_attribute.另外,由于您可能要针对多个模型执行此操作,因此可以直接猴子修补该方法,如下所示:

You can override item_before_change on your versioned model so you don't call the uploader accesor directly and use write_attribute instead. Alternatively, since you might want to do that for several models, you can monkey-patch the method directly, like this:

module PaperTrail
  module Model
    module InstanceMethods
      private
        def item_before_change
          previous = self.dup
          # `dup` clears timestamps so we add them back.
          all_timestamp_attributes.each do |column|
            previous[column] = send(column) if respond_to?(column) && !send(column).nil?
          end
          previous.tap do |prev|
            prev.id = id
            changed_attributes.each do |attr, before|
              if defined?(CarrierWave::Uploader::Base) && before.is_a?(CarrierWave::Uploader::Base)
                prev.send(:write_attribute, attr, before.url && File.basename(before.url))
              else
                prev[attr] = before
              end
            end
          end
        end
    end
  end
end

不确定这是否是最好的解决方案,但似乎可行.

Not sure if it's the best solution, but it seems to work.

这篇关于Papertrail和载波的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 14:33