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| %>
<% 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 ,[email protected],""
Brian,Oliveri Design ,[email protected],727-537-9617
LocalShopperJenn,Jennifer M Gentile ,[email protected],""
In order to seed the database with the information from the CSV file, you will need to know the file path where your CSV file is located. To me it made the most sense to place by CSV file in the lib folder in my Rails API project directory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With