In my latest project I need to export some data into a CSV file from DB dump. I have created a simple script to do that.

require 'csv'

file = "#{Rails.root}/public/user_data.csv"

users = User.order(:first_name)

column_headers = ["User ID", "First Name", "Last Name", "Email"], 'w', write_headers: true, headers: column_headers) do |writer|
  users.each do |user|
    writer << [, user.first_name, user.last_name,]

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 :)