【发布时间】:2015-03-25 05:57:00
【问题描述】:
我得到 缺少模板帖子/下载,应用程序/下载 {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[ :erb, :builder, :raw, :ruby, :coffee, :jbuilder]}。在以下位置搜索:*“/home/raj/Downloads/carrierwave/app/views” 运行应用程序时出错。
这是我的控制器:
class PostsController < ApplicationController
require "tmpdir"
require 'zip'
TmpDir = "/path/to/tmp/dir"
before_action :set_post, only: [:show, :edit, :update, :destroy]
# action method, stream the zip
def download # silly name but you get the idea
generate_zip do |zipname, zip_path|
File.open(zip_path, 'rb') do |zf|
# you may need to set these to get the file to stream (if you care about that)
# self.last_modified
# self.etag
# self.response.headers['Content-Length']
self.response.headers['Content-Type'] = "application/zip"
self.response.headers['Content-Disposition'] = "attachment; filename=#{zipname}"
self.response.body = Enumerator.new do |out| # Enumerator is ruby 1.9
while !zf.eof? do
out << zf.read(4096)
end
end
end
end
end
# Zipfile generator
def generate_zip(&block)
invoice = Post.find(params[:post_id])
photos = invoice.post_attachments
# base temp File.dirname(__FILE__)
tmp_dir = Dir.mktmpdir
# path for zip we are about to create, I find that ruby zip needs to write to a real file
zip_path = File.join(tmp_dir , 'export.zip')
Zip::File::open(zip_path, true) do |zipfile|
photos.each do |photo|
zipfile.get_output_stream(photo.avatar.identifier) do |io|
io.write photo.avatar.file.read
end
end
end
# yield the zipfile to the action
block.call 'export.zip', zip_path
ensure
# clean up the tempdir now!
FileUtils.rm_rf tmp_dir if tmp_dir
end
在 routes.rb 中:
get '/posts/download/:post_id' => 'posts#download', as: :download_post
在我的索引文件中:
<% @posts.each do |post| %>
<%= link_to "Download", download_post_path(post.id) %>
<% end %>
我还检查了 rake 路线,我得到了:
download_post GET /posts/download/:post_id(.:format) posts#download
我不知道哪里出错了。请帮忙。而且我不想使用模板,它应该只使用方法。
【问题讨论】:
-
没有下载视图,所以报错
-
@SRDP - 我不想在这里查看,我只想要一个可以下载文件的方法。
-
在这种情况下,只需重定向到原始页面。
标签: ruby-on-rails