21

I need export data as CSV in rails appl. I found this plugin: https://github.com/crafterm/comma. Do you know about some better solution?

boblin
  • 3,541
  • 4
  • 25
  • 29

2 Answers2

38

If using Ruby 1.9.x, then use CSV rather than FasterCSV and stick with the default delimiters.

Controller:

respond_to do |format|
  ...           
  format.csv { render :layout => false }
end

show.csv.erb:

<%= this_is_your_view_helper_method.html_safe %>

controller_helper.rb:

require 'csv'

def this_is_your_view_helper_method
  CSV.generate do |csv| 
    Product.find(:all).each do |product|
      csv << ... add stuff here ...
    end
  end
end
pguardiario
  • 53,827
  • 19
  • 119
  • 159
hade
  • 1,715
  • 1
  • 16
  • 24
  • 10
    FasterCSV actually became the standard CSV library in Ruby 1.9, so no need to download it, it's already there if you're on Ruby 1.9. – Fletch Dec 15 '10 at 14:48
  • 1
    Works great with rails 3.x too. – David Radcliffe May 09 '11 at 14:04
  • 1
    Thanks @Fletch for the note! This answer has been downvoted twice and I have no idea why. If you downvote, please let me know why you're doing so. – hade Mar 05 '12 at 07:29
2

Checkout this Stack Overflow answer for using CSV in Ruby 1.9.x (which, as Fletch noted, includes FasterCSV but with slightly different syntax).

Community
  • 1
  • 1
douglasr
  • 1,894
  • 1
  • 23
  • 29