/ export

Export data to CSV file from Rails console

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"]

CSV.open(file, 'w', write_headers: true, headers: column_headers) do |writer|
  users.each do |user|
    writer << [user.id, user.first_name, user.last_name, user.email]
  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 :)

Sampat Badhe

Sampat Badhe

I am a ROR developer, Rubyist, Node.js developer. I enjoy building innovative applications and currently in love with TDD practice. I am practicing agile and love to collaborate...

Read More