Last active
November 28, 2016 15:15
-
-
Save fny/acc2cc5b905e4df6f189 to your computer and use it in GitHub Desktop.
Dump Active Record Relation to CSV
This file contains 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 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