Skip to content

Instantly share code, notes, and snippets.

@fny
Last active November 28, 2016 15:15
Show Gist options
  • Save fny/acc2cc5b905e4df6f189 to your computer and use it in GitHub Desktop.
Save fny/acc2cc5b905e4df6f189 to your computer and use it in GitHub Desktop.
Dump Active Record Relation to CSV
require 'csv'
def dump_relation(file_name, relation)
File.open(file_name, 'w') do |file|
# Load the data once
records = relation.to_a
# Write headers
file.puts records.first.attributes.keys.to_csv
# Write records
records.each { |record| file.puts record.attributes.values.to_csv }
end
true
end
def dump_big_relation(file_name, relation)
File.open(file_name, 'w') do |file|
# Write headers
file.puts relation.first.attributes.keys.to_csv
# Write records
records.find_each { |record| file.puts record.attributes.values.to_csv }
end
true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment