I am bumping into an issue in my Rails app where a .csv export of data from a table is not formatting correctly.
First of all, here is the code that generates the .csv export...
report_controller.erb
class Admin::ReportController < ApplicationController
def index
@report = Report.all
respond_to do |format|
format.html
format.csv do
headers['Content-Disposition'] = "attachment;
filename=\"report-summary.csv\""
headers['Content-Type'] ||= 'text/csv'
end
end
end
end
index.csv.erb
<%- headers = ["Report Id", "Datetime", "Latitude", "Longitude", "Report Type"] -%>
<%= CSV.generate_line headers -%>
<%- @report.each do |report| -%>
<%- row = [report.id, report.datetime, report.latitude, report.longitude, report.report_type.report_type] -%>
<%= CSV.generate_line row -%>
<%- end -%>
As I was building this out, everything was working fine, until I got to the last column in the table, 'Report Type'. Here's what happens when that gets added:
Notice how that first entry has the HTML " leading and trailing? But the next one doesn't? And how the first one is distributed across additional headerless columns? And how the last one doesn't have the " but does have & in the middle (for an ampersand, of course)?
All of these values are stored as text in a ReportType table and they come through as strings in Rails and, as far as I can tell, there is absolutely nothing different about their data types anywhere, yet they are behaving differently when pulled out of the table.
If I take 'Report Type' out of the export, see how lovely my table is?
No skipped lines or anything!
It seems to me that these HTML characters - especially the leading and trailing double quotes - are causing at least some of the trouble here. I tried using .gsub('"', '') to remove them, but this has no effect.
Has anyone encountered this before or have any insight here?

