Last active
December 11, 2021 00:05
-
-
Save MyklClason/f6ac68ca4ce1faa5d655abfb0abe788b to your computer and use it in GitHub Desktop.
CSV Export (Rails)
This file contains hidden or 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
# 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) %> |
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
Just an FYI this needs tweaked to support only making a CSV of a subset of the model.