There are times when we are working on something in a rails console, and we need to push the data out to a .csv
file, for any future reference.
The below sample of code can help you achieve the same easily.
require 'csv' # Require the CSV library, since we'll be manipulating a CSV file.
file = "#{Rails.root}/public/csv_file.csv" # a file to add the data into
versions = ActiveRecord::Base.connection.execute 'select item_id, item_type from versions;' # your data to be written to the file
column_headers = %w[item_id item_type]
CSV.open(file, 'w', write_headers: true, headers: column_headers) do |writer|
versions.each do |version|
writer << [version['item_id'], version['item_type']]
end
end
And done!