Rails3 CSV put "& quot; instead of actual quotes

Similar to this question , except that I do not use html_safe anywhere in the whole project.

I create a CSV file in index.csv.erb as follows:

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

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

Example result file:

 Nicolas, Nico Joe, &quot;&quot; 

How can I prevent this?

+4
source share
2 answers

The problem is that you are not using html_safe . Your alias field is empty and converted to "" in the csv file, but it is considered unsafe with Rails and html.

Just call html_safe as a 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 contacted no longer works with Rails 3, because by default all strings are considered unsafe, which was not in Rails 2.

+14
source

refactoring

Benoit is absolutely right and thanks for this tip. Having looked at your code, I see a much cleaner approach to generating your CSV, which, as I thought, I would share for those who have landed here (for example, me!):

 <%= response.content_type = 'application/octet-stream' @persons.collect{ |person| [ person[:name], person[:nickname] ].to_csv }.join.html_safe %> 

In fact, you do not need everything that CSV generates. Ruby can take an Array and turn it into a CSV string, and then just use collect and join to make things good.

You can also do the following if you prefer it on separate lines, which I do:

 <% response.content_type = 'application/octet-stream' -%> <% @persons.each do |person| -%> <%= [ person[:name], person[:nickname] ].to_csv( row_sep: nil ).html_safe %> <% end -%> 

Here you need to use -%> to make sure you are not getting extra empty lines, and you need to use the row_sep: nil option so that to_csv does not add \n to the end of each line.

In any case, I hope this helps cleanse some people.

0
source

All Articles