LoginSignup
0
0

More than 3 years have passed since last update.

GAE/ActiveStorage/wicked_pdf/image_tagが機能しない

Posted at

環境

  • rails 5.2
  • ruby 2.5
  • ActiveStorageの保存先としてGCS(Google Cloud Storage)
  • htmlのPDF化にwicked_pdf
  • Bank Model にstampをattach

問題

  • image_tag
  • wicked_pdf_image_tag

共に画像を表示できない?
wicked_pdfがGCSへ直接アクセスできない?

結論

画像をGCSからローカル(今回の場合はGAE)のtmpファイルへダウンロードしてからPDFを生成する。

Step1 ヘルパーに以下を追記

application_helper.rb
  def wicked_image_active_storage_workaround( stamp )
    if stamp.is_a? ActiveStorage::Attachment
      save_path = Rails.root.join( "tmp", "#{stamp.id}.jpg")
      File.open(save_path, 'wb') do |file|
        file << stamp.blob.download
      end
      return save_path.to_s
    end
  end

Step2 PDFのViewでヘルパーを使用

view.pdf.erb
image_tag(wicked_image_active_storage_workaround(@bank.stamp.attachment)

STEP3 tmpファイルのデータを削除(after_actionを使用)

controller.rb
after_action :tmp_stamp_clear

  def tmp_stamp_clear
    if File.exist?(Rails.root.join( "tmp", @bank.stamp.blob.filename.to_s))
      File.delete(Rails.root.join( "tmp", @bank.stamp.blob.filename.to_s))
    end
  end

試して失敗したこと

以下の内容を試す
①image_tagへ直接書き込む
image_tag(ActiveStorage::Blob.service.send(:path_for, @bank.stamp.blob.key)
ローカル→OK
GAE→NG(
ActionView::Template::Error (undefined method path_for' for #<ActiveStorage::Service::GCSService:,,,,,,,,>):"

②HTML imgへ直接書き込む

view.html
<img src="<%= file.service_url %>">

→うまくいかない

参考URL

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0