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 -%>
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.
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