【问题标题】:How can I make 2 uploader to point to 1 cloudinary file when using carrierwave?使用carrierwave时如何让2个上传者指向1个云文件?
【发布时间】:2015-08-27 07:02:42
【问题描述】:

我有Image 模型:

class Image < ActiveRecord::Base
  mount_uploader :file, ModuleImageUploader
end

上传图片我使用carrierwave + cloudinary:

class ModuleImageUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave

  process :resize_to_limit => [700, 700]

  version :mini do
    process :resize_and_pad => [50, 50, '#ffffff']
  end

  version :thumb do
    process :resize_and_pad => [100, 100, '#ffffff']
  end

  def public_id
    return SecureRandom.uuid
  end
end

我创建了新模型AccountMediaContent

class AccountMediaContent < ActiveRecord::Base
  mount_uploader :image, AccountMediaContentImageUploader
end

它的上传器也使用carrierwave:

class AccountMediaContentImageUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave

  process :resize_to_limit => [700, 700]

  version :mini do
    process :resize_and_pad => [50, 50, '#ffffff']
  end

  version :thumb do
    process :resize_and_pad => [100, 100, '#ffffff']
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end
end

现在我需要将图像从Image 传输到AccountMediaContent。所以,这意味着如果我在 Image 中有这样的文件:

http://res.cloudinary.com/isdfldg/image/upload/v1344344359/4adcda41-49c0-4b01-9f3e-6b3e817d0e4e.jpg

这意味着我在 AccountMediaContent 中需要完全相同的文件,因此指向该文件的链接将是相同的。有什么方法可以实现吗?

【问题讨论】:

    标签: ruby-on-rails carrierwave cloudinary


    【解决方案1】:

    对此的最佳解决方案是拥有一个代表图像的新模型,然后将其链接到两个模型。

    【讨论】:

      【解决方案2】:

      好吧,我的解决方案不是很好,但无论如何。我所做的是我编写了在 Cloudinary 中下载现有图像 Image 的脚本,然后我将它们附加到新模型 AccountMediaContent

      我的任务如下所示:

      Image.find_in_batches do |imgs_in_batch|
        imgs_in_batch.each do |img|
      
          # Downloading image to tmp folder (works on heroku too)
          file_format = img.file.format
          img_url = img.file.url
          tmp_file = "#{Rails.root.join('tmp')}/tmp-img.#{file_format}"
      
          File.open(tmp_file, 'wb') do |fo|
            fo.write open(img_url).read
          end
      
          # Creating AccountMediaContent with old image (it'll be uploaded to cloudinary.
          AccountMediaContent.create(image: File.open(tmp_file))
      
          FileUtils.rm(tmp_file)
        end
      end 
      

      希望它对某人有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-05
        • 1970-01-01
        • 1970-01-01
        • 2015-05-12
        • 1970-01-01
        • 1970-01-01
        • 2013-06-30
        相关资源
        最近更新 更多