Skip to content

Instantly share code, notes, and snippets.

@KHCode
Created December 2, 2024 20:05
Show Gist options
  • Save KHCode/2342b953739bbaa085a2cb18cc17e181 to your computer and use it in GitHub Desktop.
Save KHCode/2342b953739bbaa085a2cb18cc17e181 to your computer and use it in GitHub Desktop.
Generating an Excel File From a Hash in Rails
# Pulling the data from the db
@active_record_objects = ActiveRecordObject.where(is_something: [false, nil])
# Turning the data into hashes for your own purposes
hashes = @active_record_objects.map do |object|
{ name: object.vendor.name,
data1: object.data1,
data2: object.data2,
data3: object.data3 }
end
# Generating the csv file
column_names = hashes.first.keys
path = 'hashes.csv'
CSV.open(path, 'w', headers: column_names, write_headers: true) do |csv|
hashes.each do |hash|
csv << hash.values
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment