Created
December 2, 2024 20:05
-
-
Save KHCode/2342b953739bbaa085a2cb18cc17e181 to your computer and use it in GitHub Desktop.
Generating an Excel File From a Hash in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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