DEV Community

José Anchieta
José Anchieta

Posted on

7 1

Download a CSV file from Heroku using Rails console

If you need to download some data from Heroku as i did, here is a helpful command to do it.

First, i will create a Ruby file to execute what i need in the Rails console, for example:

report = CSV.generate do |csv|
  csv << ["name", "email"]

  users = User.where(
    :created_at => Date.parse("01-11-2020")..Date.parse("30-11-2020")
  )

  users.each do |user|
    csv << [user.name, user.email]
  end
end

STDOUT.puts report

Enter fullscreen mode Exit fullscreen mode

In this case, i'm selecting all users created from November 1st until the 30th of November and exporting a csv file with all users names and emails.

In order to run this script in a Heroku Rails console and download this CSV file, we are going to use the Rails runner command.

cat users.rb | heroku run --no-tty --app=heroku-app-name -- bin/rails runner - > users.csv
Enter fullscreen mode Exit fullscreen mode

If you have NewRelic installed in your Rails application on Heroku, probably you will get some limes from it inside your CSV file. To fix that, add this grep option in our command:

cat users.rb | heroku run --no-tty --app=heroku-app-name -- bin/rails runner - | grep -v "\*\* \[NewRelic\]" > users.csv
Enter fullscreen mode Exit fullscreen mode

That's it.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay