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)

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay