Simple CSV exports for Rails

I’ve written a simple CSV exporting class that you can use in your Rails apps. It’s very useful for rending a collection of models models into CSV and providing them as download to the users of your app.

Check out the code here:

It assumes you always want to have headers in your export, so specifying the headers is required. Then, you can either render a collection of records, or add random data per row.

It’s not a gem (yet), as you can just copy and paste the code into your own app.

Here’s a sample for rendering a collection of ActiveRecord objects and offering them for download in the browser:

class CustomersController < ApplicationController

  def index
    @customers = Customer.all

    respond_to do |format|
      format.csv do
        export = :id, :name
        send_data export.render_collection(@customers), type: "text/csv"



This would return a file with the following contents, assuming we have two Customer records: Michiel and John.


This works because we assume that the records in instance variable @customers have columns or virtual attributes id and name available. If a given heading is not available, the class will raise a CsvExport::Error.

Have fun using this class! The only addition I would like to add is that you can specify other names for the column headers than the fields or methods on your records are called.