Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails3 CSV putting "" instead of actual quotes

Similar to this question except I don't use html_safe anywhere in the whole project.

I generate a CSV file in index.csv.erb like this:

<%=
response.content_type = 'application/octet-stream'
CSV.generate do |csv|
  @persons.each do |person|
    csv << [ person[:name], person[:nickname] ]
  end
end
%>

PROBLEM: If nickname is NULL in the database (ActiveRecord/MySQL) then the CSV file associated element becomes &quot;&quot;. I would expect "", or even nothing at all.

Result file sample:

Nicolas, Nico
Joe, &quot;&quot;

How can I prevent this from happening?

like image 588
Nicolas Raoul Avatar asked Dec 09 '22 06:12

Nicolas Raoul


1 Answers

The problem here is that you're not using html_safe. Your nickname field is blank and converted to "" in the csv file, but it is deemed unsafe by Rails and html escaped.

Just call html_safe on the result:

<%=
response.content_type = 'application/octet-stream'
CSV.generate do |csv|
  @persons.each do |person|
    csv << [ person[:name], person[:nickname] ]
  end
end .html_safe
%>

The solution you linked to does not work anymore with Rails 3 because all strings are considered unsafe by default, which was not the case in Rails 2.

like image 155
Benoit Garret Avatar answered Dec 31 '22 12:12

Benoit Garret