【问题标题】:Rendering a CSV sends a file (as if I used send_data) instead of rendering a text呈现 CSV 发送文件(就像我使用 send_data 一样)而不是呈现文本
【发布时间】:2012-10-31 20:47:22
【问题描述】:

以下代码返回一个people.csv 文件而不是呈现文本。如果我不使用 respond_to 块并简单地呈现文本,浏览器将按预期工作。是什么迫使浏览器在文件中发送数据?正如预期的那样,mime 类型是“text/csv”。

# /app/controllers/people_controller.rb
class PeopleController < ApplicationController
  def index
    respond_to do |format|
      format.csv { render text: "Hello, world" }
    end
  end
end

推论:渲染 xls,这是一个正确注册的 mime 类型,带有模板强制渲染 application.html,这对我来说看起来很奇怪。

# /app/controllers/people_controller.rb
class PeopleController < ApplicationController
  def index
    respond_to do |format|
      format.xls
    end
  end
end

.

# /app/views/people/index.xls.erb
<table border="1">
  <tr>
    <th>ID</th>
    <th>Name</th>
  </tr>
  <% @people.each do |person| %>
  <tr>
    <td><%= person.id %></td>
    <td><%= person.name %></td>
  </tr>
  <% end %>
</table>

【问题讨论】:

  • 我注意到这种行为在所有浏览器上都不相同。例如,它应该在 chrome 上按预期工作。
  • 我在 Chrome 中工作,但它仍然按照我描述的方式运行。

标签: ruby-on-rails csv mime-types actionview


【解决方案1】:

第一部分的答案是用content_type强制text/plain mime-type,像这样:

respond_to do |format|
  format.csv { render text: "Hello, world", content_type: 'text/plain' }
end

【讨论】:

  • 感谢 Alexei,这解决了我在返回 Railscast episode 362 后遇到的问题。有谁知道为什么会出现这种差异?假设这是 Rails 3.2 和 Rails 4.2 之间渲染工作方式的变化?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 2018-04-04
  • 2011-06-26
  • 2011-03-27
相关资源
最近更新 更多