Generate CSV from Rails console (Heroku)

Config the following file and save it with some name file.rb:

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 << [,]

STDOUT.puts report

Then run the following in the terminal:

cat file.rb \
  | heroku run --no-tty --app=heroku-app-name -- bin/rails runner - \
  | grep -v "\*\* \[NewRelic\]" -v "DISABLE_DATADOG_AGENT" \
  > results.csv


  • cat file.rb: reads the code for piping into Heroku or some other Rails console process
  • heroku run ...: the console itself. It could be another console (e.g AWS, GCP or local). --no-tty is used for preventing characters used for user interaction. Replace --app with the name of the app.
  • grep ... NewRelic: this removes those annoying booting lines from 3rd-party libs in Rails.
  • > results.csv: write the results from the Rails console into a CSV file.