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

问题描述 投票:2回答:2

在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: '[email protected]', subject: "email subject"
end

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

Question One:

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

I can use the following instead:

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

Question Two:

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

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

ruby-on-rails-5 actionmailer rails-activestorage
2个回答
2
投票

在mailer.rb中:

  @filename = object.image.attached? ? object.id.to_s + object.filename.extension_with_delimiter : nil
  if ActiveStorage::Blob.service.respond_to?(:path_for)
    attachments.inline[@filename] = File.read(ActiveStorage::Blob.service.send(:path_for, object.image.key))
  elsif ActiveStorage::Blob.service.respond_to?(:download)
    attachments.inline[@filename] = object.image.download
  end

在邮件视图中:

if @filename
  image_tag(attachments[@filename].url)
else
  image_tag(attachments['placeholder.png'].url)
end

0
投票

这对我使用Amazon S3进行生产。

在邮件视图中:

if @object.images
  @object.images.each do |image|
    path = "https://www.example.com" + Rails.application.routes.url_helpers.rails_blob_path(image, only_path: true)
    <img src="<%=path%>">
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.