Codementor Events

Export Records to CSV Files with Rails

Published Jan 17, 2017Last updated May 26, 2019
Export Records to CSV Files with Rails

Learn how to export records into CSV files using Ruby on Rails. Here are the steps.

Steps:

  1. Add a controller and make sure you handle the csv request.
  2. Add a route to point to your controller
  3. Add a model with the class method to_csv

Lets code it!

Controller

# users_controller.rb

class UsersController < ApplicationController
  def index
    @users = User.all

    respond_to do |format|
      format.html
      format.csv { send_data @users.to_csv, filename: "users-#{Date.today}.csv" }
    end
  end

Routes

# routes.rb

...

resources :users, only: :index

...

Model

# user.rb

class User < ActiveRecord::Base
  def self.to_csv
    attributes = %w{id email name}

    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |user|
        csv << attributes.map{ |attr| user.send(attr) }
      end
    end
  end

  def name
    "#{first_name} #{last_name}"
  end
end

Core custom methods:

to_csv will map out the "id, email, name" values of your model collection and then generate a CSV string.


Rails core methods for this feature:

#send_data Sends the given binary data to the browser. This method is similar to render :text => data, but also allows you to specify whether the browser should display the response as a file attachment (i.e. in a download dialog) or as inline data. You may also set the content type, the apparent file name, and other things. Source

Discover and read more posts from Victor H
get started
post commentsBe the first to share your opinion
Cristian
3 years ago

Thanks for this. I’m writing a post about modifying the response to stream the output line by line so PaaS like Heroku does not time out on big/slow output.
Also, I found a tip on ActiveRecord fetchs, using #find_each instead of #each to do batch fetching on the DB.

Antonio Jimenez
3 years ago

Thank you for this! It really helped me and it’s working now. Quick feedback: Could you please add to your examples the require 'csv', please?

It might be obvious but for a rails beginner as myself is very valuable as I spent several minutes trying to solve the problem :)

Show more replies