Created
January 28, 2019 13:04
-
-
Save walerian777/6e140f25aec8c338a1e2bec6b80eb78d to your computer and use it in GitHub Desktop.
Dump ActiveRecord::Relation to CSV
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
def csv_dump(relation:, file_path: nil) | |
file_path ||= "#{relation.table.name}.csv" | |
CSV.open(file_path, 'wb') do |csv| | |
csv << relation.klass.attribute_names | |
relation.each do |record| | |
csv << record.attributes.values | |
end | |
end | |
end | |
# Example | |
subscriptions = Subscription.where(account_id: 123) | |
csv_dump(relation: subscriptions) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment