Last active
May 26, 2020 19:42
-
-
Save dukedorje/33ae964bb18c308e1c7839e10d169b6e to your computer and use it in GitHub Desktop.
ActiveRecord: Write a CSV of a model
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
require 'csv' | |
def write_model_csv(model_class, filename=nil) | |
filename = model_class.to_s.underscore.pluralize + '.csv' if filename.nil? | |
CSV.open(filename, 'wb') do |csv| | |
names = model_class.columns.map(&:name) | |
csv << names | |
model_class.find_each do |model| | |
csv << names.map {|attr| model[attr] } | |
end | |
end | |
puts "CSV for #{model_class.to_s} written to #{filename}." | |
end | |
write_model_csv(User) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment