Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Export table to CSV with all attributes in rails console
require 'csv'
file = "#{Rails.root}/public/data.csv"
table = User.all;0 # ";0" stops output. Change "User" to any model.
CSV.open( file, 'w' ) do |writer|
writer << table.first.attributes.map { |a,v| a }
table.each do |s|
writer << s.attributes.map { |a,v| v }
end
end
@willhaslett

This comment has been minimized.

Copy link

@willhaslett willhaslett commented Jan 27, 2020

Thanks for this! Also, it can be readily modified into a Rake task that takes the model name as an argument, like rake dump_table[Foo]

require 'csv'

desc 'Dumps all records for a passed-in model to CSV. BE CAREFUL!'
task :dump_table_to_csv, [:model] => :environment do |t, args|
  model = eval(args[:model])
  file = "#{Rails.root}/public/data.csv"
  table = model.send('all') 
  CSV.open( file, 'w' ) do |writer|
    writer << table.first.attributes.map { |a,v| a }
    table.each do |s|
      writer << s.attributes.map { |a,v| v }
    end
  end
end
@andriibureviy

This comment has been minimized.

Copy link

@andriibureviy andriibureviy commented Sep 3, 2021

how to connect it to your project?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment