Responding to CSV in Rails 3 with comma
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.
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.