Rails 3.1 generates a CSV file

I can export the table data to a CSV file, however there is an empty line after each record. Why and how to 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 -%> 
+6
source share
5 answers

This is what is fixed.

 <%= CSV.generate_line row, :row_sep => ?\t, :quote_char => ?\ %> 
+6
source

CSV.generate_line adds a new line character to the end of the line it creates, but also has the value <%= %> , so you get two new lines.

To suppress a new line character from the output of an erb expression, 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 goes to a new line generated from erb , but suppresses a new line from CSV.generate_line , which, in my opinion, is not the best way to do this.

+6
source

for me after using the strip and html_safe work applied after creating the string:

 <%- headers = ["Id", "Tour No"] -%> <%= CSV.generate_line(headers).strip%> <%- @tours.each do |t| -%> <%- row = [ t.id,t.tour_no] -%> <%= CSV.generate_line(row).html_safe.strip%> <%- end -%> 
+2
source

Try the following:

 row = [ n.id, n.fname.strip ] 

strip will remove \ r and / or \ n, which can lead to empty lines. I have no other explanation that your source code is fine!

0
source

I thought I could end my decision just by fighting it.

Basically, everything worked perfectly on my local machine (Mac), and then, when I deployed my application to the hero, he began to add new lines to these new secrets.

For me, the solution was to use:

 CSV.generate_line(row, row_step: ?\r).html_safe 

As a side note, I'm using rails 4.1.6.

Hope that helps some other people struggling

0
source

Source: https://habr.com/ru/post/899548/


All Articles