1
Write a post

Export Records to CSV Files using Rails

Published Jan 17, 2017Last updated Feb 22, 2017
Export Records to CSV Files using 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 and 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 Alfonso Hazbun Anuff
get started
Enjoy this post?

Leave a like and comment for Victor

1
Be the first to share your opinion

Subscribe to our weekly newsletter