Skip to content

Instantly share code, notes, and snippets.

@bonafernando
Created August 13, 2019 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bonafernando/3993ca816879875a15230885983facb0 to your computer and use it in GitHub Desktop.
Save bonafernando/3993ca816879875a15230885983facb0 to your computer and use it in GitHub Desktop.
Rails controller snippet to send csv report of a query
require "csv"
@query = Model.where(field: "condition")
result_csv = CSV.generate(headers: true) do |csv|
csv << @query.first.attributes.keys
@query.find_each do |row|
csv << row.attributes.values
end
end
send_data(result_csv, filename: "model_report_#{Date.current.to_s}.csv")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment