Export data to CSV file from Rails console
1 min readOct 16, 2015
In one of my project I would like to dump and export some information into a CSV file. I have produced an easy script to do that.
require 'csv' file = "#{Rails.root}/public/product_data.csv"products = Product.order(:first_name)headers = ["Product ID", "Name", "Price", "Description"]CSV.open(file, 'w', write_headers: true, headers: headers) do |writer|
products.each do |product|
writer << [product.id, product.name, product.price, product.description]
end
end
Here is what the above snippet does:
- Require the CSV library, since we’ll be manipulating a CSV file.
- Create file path where we need to store this CSV.
- Fetch the records from the DB which we have to put it into the CSV.
- Open that file in write mode.
- Iterate over the records to write each record in the CSV.
- And finally access that file.
Hope this will help you all :)
Originally published at https://blog.kiprosh.com on October 16, 2015.