Ruby on rails 即使在我添加路由时也缺少模板错误
我得到了缺少的模板帖子/下载,应用程序/下载带有{:locale=>[:en],:formats=>[:html],:variants=>[],:handlers=>[:erb,:builder,:raw,:ruby,:coffee,:jbuilder]}。搜索:“/home/raj/Downloads/carrierwave/app/views”运行应用程序时出错 这是我的控制器:Ruby on rails 即使在我添加路由时也缺少模板错误,ruby-on-rails,Ruby On Rails,我得到了缺少的模板帖子/下载,应用程序/下载带有{:locale=>[:en],:formats=>[:html],:variants=>[],:handlers=>[:erb,:builder,:raw,:ruby,:coffee,:jbuilder]}。搜索:“/home/raj/Downloads/carrierwave/app/views”运行应用程序时出错 这是我的控制器: class PostsController < ApplicationController require
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
在我的索引文件中:
<% @posts.each do |post| %>
<%= link_to "Download", download_post_path(post.id) %>
<% end %>
我不知道哪里出了问题。请帮忙。我不想使用模板,它应该只使用方法。尝试在下载操作中添加这一行
render :nothing => true, :status => 200, :content_type => 'text/html'
或者重定向到某个页面
希望对你有所帮助一个行动必须要有结果。。。。。 如果它不打算呈现任何内容,您应该提到:
render :nothing => true
因为,在您的案例中,您希望此操作提供一个文件供下载。我建议您使用send_file
方法。它会让你的生活变得轻松
以下链接将帮助您实现这一点:
没有下载视图,因此它会抛出error@SRDP-我不想在这里查看,我只想要一个可以下载文件的方法。在这种情况下,只需重定向到原始页面。
render :nothing => true, :status => 200, :content_type => 'text/html'
render :nothing => true