Skip to content

Instantly share code, notes, and snippets.

@dukejones
Last active May 26, 2020 19:42
Show Gist options
  • Save dukejones/33ae964bb18c308e1c7839e10d169b6e to your computer and use it in GitHub Desktop.
Save dukejones/33ae964bb18c308e1c7839e10d169b6e to your computer and use it in GitHub Desktop.
ActiveRecord: Write a CSV of a model
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