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/user_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:

  1. Require the CSV library, since we'll be manipulating a CSV file.
  2. Create file path where we need to store this CSV.
  3. Fetch the records from the DB which we have to put it into the CSV.
  4. Open that file in write mode.
  5. Iterate over the records to write each record in the CSV.
  6. And finally access that file.

Hope this will help you all :)