PaperClip - 保存新附件而不删除旧附件

时间:2011-11-09 16:47:25

标签: ruby-on-rails paperclip

我在Rails 3上使用Paperclip(带有Amazon s3)。我想在不更换旧文件的情况下将新文件附加到我的模型中。我不希望旧文件可以访问,我只想在s3上作为备份。 你知道是否有办法告诉回形针自己处理它?<​​/ p> post.rb中的

我有:

has_attached_file :sound,
        :storage => :s3,
        :s3_credentials => "....",
        :styles => {:mp3 => {:format => :mp3}},
        :processors => [:sound_processor],
        :s3_host_alias => '....',
        :bucket => '....',
        :path => ":attachment/:id/:style/out.:extension",
        :url => ":s3_alias_url"

,处理器如下:

class Paperclip::SoundProcessor < Paperclip::Processor

  def initialize file, options = {}, attachment = nil
    super

    @format = options[:format] || "mp3"
    @current_format = File.extname(@file.path)
    @basename = File.basename(@file.path, @current_format)
  end

  def make
    src = @file
    dst = Tempfile.new([@basename,".#{@format}"])
    dst.binmode

    cmd = "ffmpeg -y -ab 128k -t 600 -i #{File.expand_path(src.path)} #{File.expand_path(dst.path)}"
    Paperclip.log(cmd)
    out = `#{cmd}`
    raise Paperclip::PaperclipError, "processor does not accept the given audio file" unless $?.exitstatus == 0

    dst
  end

end

3 个答案:

答案 0 :(得分:4)

这就是我的工作。我在保存之前对文件名加时间戳(以防止另一个同名文件覆盖原文),并强制回形针永不删除任何内容。

before_create :timestamp_filename

def timestamp_filename
  fname = Time.now.to_s(:db).gsub(/[^0-9]/,'') + '_' + sound_file_name
  sound.instance_write(:file_name, fname)
end

# override paperclip's destroy files
# method to always keep them around
def destroy_attached_files
  true
end

答案 1 :(得分:0)

向您的模型添加版本控制非常简单,最近我在组合中使用CarrierWave和paper_trail来实现此目的。我们正在部署到Heroku,所以S3也在混合中。

我发布这个作为答案的原因是因为虽然有争议,但我不认为像PaperClip这样的库应该支持备份文件,专门解决这个问题的库对我个人来说感觉更好。

答案 2 :(得分:0)

这是一个很好的资源,您可以查看:http://eggsonbread.com/2009/07/23/file-versioning-in-ruby-on-rails-with-paperclip-acts_as_versioned/

它创建文件的新版本。希望这会有所帮助。