Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3.1 generating CSV file

I am able to export table data to a CSV file, however there is a blank row after every record. Why and how do i fix it?

in index.html.erb

<%= link_to "Export to csv", request.parameters.merge({:format => :csv})%>

in index.csv.erb

<%- headers = ["Id", "Name"] -%>
<%= CSV.generate_line headers %>
<%- @customers.each do |n| -%>
<%- row = [ n.id, n.fname ] -%>
<%= CSV.generate_line row %>
<%- end -%>
like image 516
ctilley79 Avatar asked Oct 18 '11 18:10

ctilley79


1 Answers

CSV.generate_line adds a new line character to the end of the line it generates, but so does <%= %> so you're getting two new lines.

To suppress the new line character from the erb expression output use this syntax: <%= -%>

so:

<%- headers = ["Id", "Name"] -%>
<%= CSV.generate_line headers -%>
<%- @customers.each do |n| -%>
<%- row = [ n.id, n.fname ] -%>
<%= CSV.generate_line row -%>
<%- end -%>

The accepted answer leaves in the new line generated from the erb but suppresses the new line from CSV.generate_line which I think is not the best way to do it.

like image 93
Toby 1 Kenobi Avatar answered Nov 02 '22 07:11

Toby 1 Kenobi