Export CSV file from rails console

In my latest project I need to dump and export some data into a csv file. I have create a simple script to do that.

Here I am sharing my script with you.

require 'csv'

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

schools = School.where(state_code: 'CO').order('name ASC')

CSV.open( file, 'w' ) do |writer|
  schools.each do |s|
    writer << [s.name, s.zipcode, s.id]
  end
end

Happy coding 🙂

Advertisements

One thought on “Export CSV file from rails console

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s