Skip to content

Instantly share code, notes, and snippets.

@MyklClason
Last active December 11, 2021 00:05
Show Gist options
  • Save MyklClason/f6ac68ca4ce1faa5d655abfb0abe788b to your computer and use it in GitHub Desktop.
Save MyklClason/f6ac68ca4ce1faa5d655abfb0abe788b to your computer and use it in GitHub Desktop.
CSV Export (Rails)
# Good solution for exporting to CSV in rails.
# Source: https://www.codementor.io/victorhazbun/export-records-to-csv-files-ruby-on-rails-vda8323q0
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
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
end
<%= link_to 'Export CSV', user_path(format: :csv) %>
@MyklClason
Copy link
Author

Just an FYI this needs tweaked to support only making a CSV of a subset of the model.

@MyklClason
Copy link
Author

ActionController::Renderers.add :csv do |csv, options|
    self.content_type ||= Mime::CSV
    self.response_body  = csv.respond_to?(:to_csv) ? csv.to_csv : csv
end

Would allow for format.csv { render csv: @communications }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment