Skip to content

Instantly share code, notes, and snippets.

@elcortez
Created November 20, 2022 13:59
Show Gist options
  • Save elcortez/67639eb273b79bf7923b3a76daa65c0d to your computer and use it in GitHub Desktop.
Save elcortez/67639eb273b79bf7923b3a76daa65c0d to your computer and use it in GitHub Desktop.
Rails - Build a CSV and send it though email
require 'csv'
def generate_users
query = "SELECT first_name, last_name FROM users"
sanitized_query = ActiveRecord::Base.sanitize_sql_array([query])
result = ActiveRecord::Base.connection.execute(sanitized_query).values
csv_string = CSV.generate do |csv|
csv << ["first_name", "last_name"]
result.map { |row| csv << row }
end
mailer = ActionMailer::Base.new
mailer.attachments["result.csv"] = csv_string
mailer.mail(
from: "[email protected]",
to: ["[email protected]"],
subject: "Users from #{Date.today.strftime('%d-%m-%Y')}",
body: "See attached"
)
mailer.message.deliver
end
generate_users
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment