Created
November 20, 2022 13:59
-
-
Save elcortez/67639eb273b79bf7923b3a76daa65c0d to your computer and use it in GitHub Desktop.
Rails - Build a CSV and send it though email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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