Maz
Maz

Reputation: 11

How to export table data as CSV file in Ruby 1.9.2 + Rails3?

I am a student that currently enrolled in a Information Technology program and have been given a project that requires my team and I to create a dynamic form builder using Rails 3 + Ruby 1.9.2. A key feature of this dynamic form builder will be for users to export the results of their form. I haven't had much success implementing the CSV feature using the CSV class defined in the Ruby 1.9+ API. I define an "export" function in the form_results controller and am currently just trying to write to a CSV file. My export function looks like this:

def export
 CSV.open("/public/results/results.csv", "wb") do |csv|
   csv << ["sample", "data"]
 end
end

And in the view, I link to the function by using:

<%= link_to 'Download CSV', form_form_results_path(@form), :method => :export %>

I feel that if I can get the implementation of the CSV class working properly, I will be able to finish off the rest of logic without any serious issues. Any guidance, input or help will be greatly appreciated.

Thanks,

Maz M.

Upvotes: 1

Views: 4800

Answers (2)

Nishant Upadhyay
Nishant Upadhyay

Reputation: 639

You should refer this link. This Railscast episode explains to export data in either CSV format or XLS format. You can also refer this link.

Upvotes: 1

johnmcaliley
johnmcaliley

Reputation: 11055

Your use of the :method param is incorrect. This should be used to specify http verbs. Documentation here: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

I would suggest using the respond_to block in the action where they are viewing the dynamic form, and use format.csv. This allows you to use the same action, but render the results in a different format by merely calling the action URL with .csv appended to the URL

respond_to do |format|
  format.html
  format.csv { render :text => @dynamic_form.to_csv} #this will return txt in browser
  #format.csv { render :csv => @dynamic_form.to_csv} #with mime type (should prompt browser download)
end

Then in your form model you can create a to_csv def which will render the csv and return it as a string. You really should not put any logic like this in your controller. Controllers are meant for creating instance variables (where creation logic should be done in models) and forwarding to the proper views. The model should contain the bulk of your logic. google "skinny controllers, fat models" for more info on that.

def to_csv
  csv = some_logic_here_to_create_csv_string
  csv
end

Your link_to call would probably look like this (just writing this off the top of my head.. I cant remember if this is the correct syntax):

<%= link_to 'Download CSV', form_form_results_path(@form, :format=>:csv) %>

Upvotes: 2

Related Questions