首页 文章

如何在Rails中的活动存储关联中附加邮件程序中的图像

提问于
浏览
1

在rails 5.2中,我有一个使用has_many_attached:images的模型 . 我想发送一封电子邮件,其中包含所有相关图像作为附件 .

我的邮件方法目前看起来像:

def discrepancy_alert(asset_discrepancy_id, options={})
  @asset_discrepancy = AssetDiscrepancy.find asset_discrepancy_id
  @asset_discrepancy.images.each_with_index do |img,i|
    attachments["img_#{ i }"] = File.read(img)
  end
  mail to: 'noone@gmail.com', subject: "email subject"
end

显然,File.read在这里不起作用,因为img不是路径,它是一个blob . 我在文档中找不到任何关于此的信息

问题一:

是否有一个rails方法来附加像这样的blob?

我可以使用以下代码:

@asset_discrepancy.images.each_with_index do |img,i|
  attachments["img_#{ i }"] = img.blob.download
end

问题二:

下载方法可以使用RAM的日志,这种用法不明智吗?

似乎,通过添加ActiveStorage,rails mailers会有一些新的方法来实现两者之间的交互....我没有在文档中看到过任何内容 . 所有邮件程序附件[]示例都使用本地文件的路径 .

1 回答

  • 0

    在mailer.rb中:

    attachments.inline[object.id.to_s + ".png"] = File.read(ActiveStorage::Blob.service.send(:path_for, object.image.key)) if object.image.attached?
    

    在邮件视图中:

    image_tag(object.image.attached? ? attachments[object.id.to_s + ".png"].url : attachments['placeholder.png'].url)
    

相关问题