1

In my result.csv.erb, I have a issue with the csv being createdas within some of the columns in the result, I get data spillage.

I have a column called title which can be be of the form Son's of fortune, or Love,Fear,Hatred. In the first case, for some reason, I get &quot in my result. In the other, the data gets split by , as default :col_sep is ,.

<%- @results.each do |result| -%>
    <%- row = result.values -%>
    <%= CSV.generate_line row, :row_sep => nil, :quote_char => "'" %>
<%end%>

For eg-: The title was Gas Shoe (Grey, Chestnut) and the result spills into the other columns

title - &quot;Gas Shoe (Grey
seller -  Chestnut)&quot;   

I am open to editing the data before insertion if absolutely necessary. So any ideas?

Pratik Bothra
  • 2,642
  • 2
  • 30
  • 44

3 Answers3

8

All strings in rails3 are unsafe by default, so you need to call #html_safe on your row. From this answer:

<%=
response.content_type = 'application/octet-stream'
CSV.generate do |csv|
  @persons.each do |person|
    csv << [ person[:name], person[:nickname] ]
  end
end .html_safe
%>
Community
  • 1
  • 1
Jeff Paquette
  • 7,089
  • 2
  • 31
  • 40
1

I would follow the advice on https://en.wikipedia.org/wiki/Comma-separated_values. There's no standard CSV format, but the section "Towards Standardization" gives some good advice. The parts that apply to you are:

  • Fields containing a line-break, double-quote, and/or commas should be quoted. (If they are not, the file will likely be impossible to process correctly).

  • A (double) quote character in a field must be represented by two (double) quote characters.

So if the field has commas, wrap it with double-quotes. If the field has a double-quote, replace it with two double-quotes. Fields with single-quotes should be wrapped in double-quotes, but otherwise do not need to be modified.

Michael Venable
  • 5,011
  • 3
  • 23
  • 20
0

you can remove that from your result using YOUR_STRING.gsub("&quot","")

Sumit Munot
  • 3,748
  • 1
  • 32
  • 51
  • 2
    Better to call .html_safe as is done here http://stackoverflow.com/questions/7358509/rails3-csv-putting-quotquot-instead-of-actual-quotes – Jeff Paquette Apr 04 '13 at 18:29