DEV Community

chair
chair

Posted on

2 2

Ruby CSV Template

I refer to this #ruby #csv template at least once a week in my day job. I hope this will also become useful for you!

This template simply loops thru an assumptive group of users in a database. The template can be easily modified for your own use.

Simply modify the desired file path, the objects you would like to loop thru, and execute the following command from the the root directory of your rails app: rails r <name_of_template>

require 'csv'

path = 'file_path.csv';
users = User.order(created_at: :desc);

CSV.open(path, "wb") do |csv|
  # headers
  csv << ['First Name', 'Last Name', 'Date of Birth'];

  # loop thru users
  users.each do |u|
    csv << [u.first_name, u.last_name, u.date_of_birth];
  end  
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay