Export to CSV in Rails

Exporting data to CSV from a Rails app is as simple as adding a respond_to block to the controller action and setting the proper response headers.

As an example, let’s consider a users#index action which lists the users for admin. Now if you want to allow the admin to download the list as CSV, this is how it can be done:

Require Ruby’s built in CSV library in ApplicationController.

require'csv'

In users#index, add a respond_to block with HTML and CSV formats. In the format.csv block, set the ‘Content-Type’ and the ‘Content-Disposition’ headers. (The latter lets you set the name of the downloaded file.)

Hi, I’m Nithin Bekal.
I work at Shopify in Ottawa, Canada.
Previously, co-founder of
CrowdStudio.in and
WowMakers.
Ruby is my preferred programming language,
and the topic of most of my articles here,
but I'm also a big fan of Elixir.
Tweet to me at @nithinbekal.