Ruby on Rails CSV put"" 而不是实际的报价

Ada*_*ard 10 csv ruby-on-rails

我正在尝试生成CSV文件.一切都很好,除了空白字段,我不太确定有""而不是实际的报价.我已经提供了用于生成文件和一些输出的代码.

<% headers = ["Username", "Name", "E-mail", "Phone Number"] %>
<%= CSV.generate_line headers %>

<% @users_before_paginate.each do |user| %>
  <% row = [ "#{user.username}".html_safe ] %>
  <% row << "#{user.profile.first_name} #{user.profile.last_name}".html_safe unless user.profile.blank? %>
  <% row << "#{user.email}".html_safe unless user.profile.nil? %>
  <% row << "#{user.profile.phone}".html_safe unless user.profile.nil? %>
  <%= CSV.generate_line row %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

产量

Username,Name,E-mail,Phone Number

  admin,LocalShopper ,shoplocally1@gmail.com,&quot;&quot;
  Brian,Oliveri Design ,brian@oliveridesign.com,727-537-9617
  LocalShopperJenn,Jennifer M Gentile ,localshopperjenn@hotmail.com,&quot;&quot;
Run Code Online (Sandbox Code Playgroud)

And*_*Vit 29

而不是在数组的每个部分上调用html_safe,然后从中生成一个新的(非html安全的)字符串,尝试在结束后调用它,从generate_line以下字符串返回后:

<%= CSV.generate_line(row).html_safe %>
Run Code Online (Sandbox Code Playgroud)

更新:为了安全起见,您需要确保此模板不是以HTML格式发送到浏览器,而是原始文本/ csv文件.如果行内容包含任何实际的HTML标记<script>,则这些标记不会被转义,因为您已将输出声明为"安全".

如果需要在HTML页面中输出此内容,那么您最好考虑正确转义而不是像这样绕过它.

考虑一下您是否真的需要一个html.erb用于生成CSV 的模板.