CSV: Responding in Rails 3 With Comma

Reading Time: < 1 minute

In one of our applications, as a feature, I had to allow users to export
certain data to a CSV file, I can show you, this is what I do

The first solution that came to my mind was to add it a 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 this.

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 file.

Know more about us!

0 Shares:
You May Also Like
Read More

Authorization

Reading Time: 4 minutes Authorization determines which actions a user can perform on an application There are a lot of alternatives which…