将Paperclip文件下载为ZIP

Awe*_*wea 5 zip ruby-on-rails paperclip

其实我做的是这样的:

project          = Project.find(params[:id])  
attachments_list = project.attachments.where{attach_file_size > 0}
assets_list      = project.assets.where{image_file_size > 0}
#Person.where{(name =~ 'Ernie%') & (salary < 50000) | (name =~ 'Joe%') & (salary > 100000)}
file_name  = project.title.downcase.gsub(' ', '_destroy')
file_name  = "#{file_name}.zip"

temp_file  = Tempfile.new("#{file_name}-#{current_user.id}")
Zip::ZipOutputStream.open(temp_file.path) do |zos|
  attachments_list.each do |file|
    zos.put_next_entry(file.title)
    zos.print IO.read(file.attach.path)
  end
  assets_list.each do |file|
    zos.put_next_entry(file.title)
    zos.print IO.read("#{file.image.path}")
  end
end

send_file temp_file.path, :type => 'application/zip',
                          :disposition => 'attachment',
                          :filename => file_name
temp_file.close
Run Code Online (Sandbox Code Playgroud)

这是工作,但收到的文件缺少扩展,任何想法?

Awe*_*wea 2

我最终在相关模型中创建了一个方法来返回带有扩展名的文件名

def title_with_ext
    "#{self.title}#{File.extname(self.image.path)}"
end
Run Code Online (Sandbox Code Playgroud)