Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Created March 9, 2017 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpowell4/f0e47321602605a692bd1e315d2e7395 to your computer and use it in GitHub Desktop.
Save danielpowell4/f0e47321602605a692bd1e315d2e7395 to your computer and use it in GitHub Desktop.
Exports records from a sample users model to csv by means of a controller action and `.csv` format. Ruby on Rails app
# Synchronously creates and sends records for download
# For scale, this would be better done async via a rake task, chron job, or something similar
# borrowed from https://gorails.com/episodes/export-to-csv
# sample controller
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
end
# sample model
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment