De453538cc7e6047d144995f0ddac38f
Mar 06, 2012

In one of our applications, as a feature, I had to allow users to export certain data to a CSV file.

The first solution that came to my mind was to add a CSV responder at the controller, that way Rails should take care of the rest for me, or so I thought.

class JobsController < ApplicationController
  respond_to :csv

  def index
    @jobs = Job.confirmed
    respond_with @jobs
  end
end

However, if you browse to '/jobs.csv' in your browser, you get a missing template error, this is because Rails can only render json, xml, and js by default.

If we need to respond with another MIME type, we need to add a custom renderer, or, use a gem like comma.

COMMA

From it's README:

When used with Rails (ie. add 'comma' as a gem dependency), Comma automatically adds support for rendering CSV output in your controllers:

So, now all we need to do is add comma to our Gemfile:

gem 'comma', '~> 3.0'

And in our model define a comma block with the desired structure for the CSV.

class Job < ActiveRecord::Base
  belongs_to :service

  comma do
    name
    scheduled_at
        ...
  end
end

Even if we need to include association attributes:

class Job < ActiveRecord::Base
  belongs_to :service

  comma do
    name
    scheduled_at
    service :name
    ...
  end
end

And that's it! now you can browse to '/jobs.csv' in your browser and you will get your CSV file.

blog comments powered byDisqus

About Crowd Interactive

Crowd Interactive is a leading Ruby and Rails consultancy firm based in Mexico currently doing business with startups in the United States.

We specialize in building and growing Rails applications, by increasing your IT crew onsite or offsite. We pick our projects carefully, as we only work with companies we believe in.

You can find out more about us on our website.

Our Favorite Sites

Our conference

Conferences we attend

Stuff we've built

Earlier Posts