加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby:Paperclip,S3和Deep-cloning

发布时间:2020-12-17 01:57:41 所属栏目:百科 来源:网络整理
导读:我有一个主题模型,其中包含许多资产.资产正在使用Paperclip并将其文件内容存储在我的Amazon AWS-S3系统中.我也使用deep_clone,因为我的客户能够复制内置的主题,然后根据他们的内容修改它们.所有deep_clone工作都很好,但是当我深入挖掘资产时,旧的文件内容不
我有一个主题模型,其中包含许多资产.资产正在使用Paperclip并将其文件内容存储在我的Amazon AWS-S3系统中.我也使用deep_clone,因为我的客户能够复制内置的主题,然后根据他们的内容修改它们.所有deep_clone工作都很好,但是当我深入挖掘资产时,旧的文件内容不会被添加到我的S3存储桶中.记录将保存到数据库中,但由于文件内容未使用新ID保存,因此file.url属性指向死文件.

我已经尝试手动调用paperclip的save和create方法,但我无法弄清楚如何让paperclip将文件“推”回桶中,因为它现在有一个新的ID等等….

require 'open-uri'

class Asset < ActiveRecord::Base
  belongs_to :theme
  attr_accessor :old_id
  has_attached_file :file,:storage => "s3",:s3_credentials => YAML.load_file("#{RAILS_ROOT}/config/aws.yml")[RAILS_ENV],:bucket => "flavorpulse-" + RAILS_ENV,:path => ":class/:id/:style.:extension"
  validates_attachment_presence :file
  validates_attachment_size :file,:less_than => 5.megabytes

  before_save :delete_assets_in_same_theme_with_same_name
  after_create :copy_from_cloned_asset

  private
  def delete_assets_in_same_theme_with_same_name
    Asset.destroy_all({:theme_id => self.theme_id,:file_file_name => self.file_file_name})
  end

  def copy_from_cloned_asset
    if (!old_id.blank?)
      if (old_id > 0)
        old_asset = Asset.find(old_id)
        if (!old_asset.blank?)
          self.file = do_download_remote_image(old_asset.file.url)
          self.file.save
        end
      end
    end
  end

  def do_download_remote_image (image_url)
    io = open(URI.parse(image_url))
    def io.original_filename; base_uri.path.split('/').last; end
    io.original_filename.blank? ? nil : io
  rescue # catch url errors with validations instead of exceptions (Errno::ENOENT,OpenURI::HTTPError,etc...)
  end
end

关于如何获取回形针来推送文件的任何想法?我也不会反对使用亚马逊的aws-s3宝石这样做,但我似乎无法让它工作.

解决方法

根据 this former question/answer,应该可以使用这个简单的代码行:

self.file = old_asset.file

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读