I am attempting to generate a CSV file. Everything is fine except for blank fields, I'm not quite sure have ""
instead of actual quotes. I've provided the code I'm using to generate the file and some output.
<% headers = ["Username", "Name", "E-mail", "Phone Number"] %>
<%= CSV.generate_line headers %>
<% @users_before_paginate.each do |user| %&开发者_运维知识库gt;
<% 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 %>
Output
Username,Name,E-mail,Phone Number
admin,LocalShopper ,shoplocally1@gmail.com,""
Brian,Oliveri Design ,brian@oliveridesign.com,727-537-9617
LocalShopperJenn,Jennifer M Gentile ,localshopperjenn@hotmail.com,""
Instead of calling html_safe on each part of the array and then making a new (non-html-safe) string from it, try calling it at the end, after the string is returned from generate_line
:
<%= CSV.generate_line(row).html_safe %>
UPDATE: For security, you need to be sure that this template is not being sent to the browser as HTML, but a raw text/csv file. If the row content contains any actual HTML tags like <script>
, these would not get escaped, because you've declared the output as "safe".
If this content needs to be output within an HTML page, then you'd better consider correct escaping instead of bypassing it like this.
Consider if you really need a html.erb
template for generating CSV.
Here's a template I've used that works well enough:
<%=
response.content_type = 'application/octet-stream'
FasterCSV.generate do |csv|
csv << @report[:columns]
@report[:rows].each do |row|
csv << row
end
end
%>
You can do this entirely within the controller if you like and render it as type :text
instead.
It also helps if you wrangle the content into order, in this case a simple @report
hash, inside the controller than to do all the heavy lifting in the view.
精彩评论