【问题标题】:Missing template error even when I added in routes即使我在路由中添加了模板错误
【发布时间】: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


【解决方案1】:

尝试在您的下载操作中添加这一行

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

或重定向到某个页面

希望对你有帮助

【讨论】:

    【解决方案2】:

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

    render :nothing => true
    

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

    以下链接将帮助您:

    How to download file with send_file?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 2017-07-25
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多