2
0

More than 3 years have passed since last update.

Active Storageでsvgを表示する【Rails】

Last updated at Posted at 2021-09-08

svg画像をActive Storageでattachしてから表示する際に少々手こずったのでメモ

svgがimgタグで表示されない

Model

hoge.rb
class Hoge < ApplicationRecord
  has_one_attached :image
  ...
end

View

= tag.img src: url_for(@hoge.image)

これだと画像として表示されない。

これを解決するには、まずRailsがデフォルトでHTTPヘッダーのContent-Dispositionをattachmentとしているリストから"image/svg+xml"を消して、inlineを許可する。

config/initializer/storage.rb
Rails.application.config.active_storage.content_types_to_serve_as_binary.delete("image/svg+xml")
Rails.application.config.active_storage.content_types_allowed_inline << "image/svg+xml"

N+1

単にrails_storage_proxy_pathとするだけだとその都度

SELECT `active_storage_blobs`.* FROM `active_storage_blobs` WHERE `active_storage_blobs`.`id` = <hoge.id> LIMIT 1

とされてしまいN+1問題が起きる。

これを解決するには、<attachment_name>_url属性をモデルに追加して

hoge.rb
attribute :image_url

def image_url
    return self.image.attached? ? url_for(self.image) : "#"
end

with_attached_<attachment_name>する。

Hoge.<queries>.with_attached_image

するとSQLのWHERE以下がイコールからIN <list>に変わる。

参考

2
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
2
0