Skip to content

Instantly share code, notes, and snippets.

@walerian777
Created January 28, 2019 13:04
Show Gist options
  • Save walerian777/6e140f25aec8c338a1e2bec6b80eb78d to your computer and use it in GitHub Desktop.
Save walerian777/6e140f25aec8c338a1e2bec6b80eb78d to your computer and use it in GitHub Desktop.
Dump ActiveRecord::Relation to CSV
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