Skip to content

Instantly share code, notes, and snippets.

@d3vkit
Forked from foxumon/csv_export.rb
Last active March 25, 2019 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d3vkit/f6037c00fb278ba39da23fa89de64ec7 to your computer and use it in GitHub Desktop.
Save d3vkit/f6037c00fb278ba39da23fa89de64ec7 to your computer and use it in GitHub Desktop.
Export table to CSV with all attributes in rails console
folder = Rails.root.join('public', 'csv', 'data')
tables = ActiveRecord::Base.connection.tables
tables.each do |table|
klass = table.classify.safe_constantize
next unless klass && klass.respond_to?(:find_each)
data = klass.scoped
next unless data.any?
file = folder.join("#{table}.csv")
CSV.open(file, 'w') do |csv|
csv << data.first.attributes.keys
data.find_each do |s|
csv << s.attributes.values.collect { |v| v unless v.to_s.encoding.name == "ASCII-8BIT" }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment