Created
March 9, 2017 22:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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