即使我在路线中添加,也会丢失模板错误

时间:2015-03-25 05:57:01

标签: 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 "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

我不知道哪里出了问题。请帮忙。而且我不想使用模板,它应该只使用方法。

2 个答案:

答案 0 :(得分:1)

尝试在下载操作中添加此行

render :nothing => true, :status => 200, :content_type => 'text/html'

或重定向到某个页面

希望有所帮助

答案 1 :(得分:0)

动作必须呈现一些东西...... 如果它不打算渲染任何东西,你应该提到:

render :nothing => true

因为,在这种情况下,您希望此操作提供要下载的文件。我建议你使用send_file方法。它会让你的生活变得轻松。

以下链接可以帮助您:

How to download file with send_file?

http://apidock.com/rails/ActionController/Streaming/send_file