ruby-on-rails – 如何在Rails中通过电子邮件发送自生成的csv文
发布时间:2020-12-16 21:13:28 所属栏目:百科 来源:网络整理
导读:在我的Rails应用程序中,我使用模型方法中的CSV.open块创建CSV文件. class SomeModel def self.write_csv CSV.open("my_file_name.csv","w") do |csv| ### inserts lines into the file ### end endend 在我的控制器中,我有一个动作将文件发送到用户输入的电
在我的Rails应用程序中,我使用模型方法中的CSV.open块创建CSV文件.
class SomeModel def self.write_csv CSV.open("my_file_name.csv","w") do |csv| ### inserts lines into the file ### end end end 在我的控制器中,我有一个动作将文件发送到用户输入的电子邮件地址 def some_controller_method SomeModel.write_csv email = params[:email] JobMailer.send_csv(email).deliver end 在JobMailer中,我直接通过文件名引用文件,因为SomeModel.write_csv中的CSV.open块将文件保存到主目录的磁盘上. def send_csv(email) attachments['my_file_name.csv'] = {mime_type: 'text/csv',content: File.read(Rails.root.join('your_file.csv'))} mail(to: email,subject: 'My subject',body: 'My body.') end 目前,当新的请求进入时,应用程序将重写该文件,我相信当我在Heroku上进行生产时,它会在一段时间后自动删除它. 回顾一下: >生成CSV 可以在不将其保存到磁盘的情况下完成吗?有没有更好的办法? 解决方法
您可以使用CSV#generate class方法
class SomeModel def self.generate_csv CSV.generate do |csv| ### inserts lines into the file ### end end end def some_controller_method csv = SomeModel.generate_csv email = params[:email] JobMailer.send_csv(email,csv).deliver end def send_csv(email,csv) attachments['my_file_name.csv'] = {mime_type: 'text/csv',content: csv} mail(to: email,body: 'My body.') end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |