現象としてlocalhost:3000/items/:idで実装している機能の動作確認を行っていたところ、variantを指定して表示したいんだけど非表示になってしまっていた。
原因:minimagickを明示的に指定していなかった
Gemfile.lockを確認するとmini_magickがちゃんとインストールされていることがわかりました。
問題はvariantを利用するためにmini_magickを明示的に指定していないことが問題なようです。
参考URL
https://zenn.dev/iloveomelette/articles/76aad4d9ce86d1
config/application.rbに以下を追記。
module Myapp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 7.0
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
config.generators do |g|
g.test_framework :rspec,
fixtures: false,
view_specs: false,
helper_specs: false,
routing_specs: false
g.factory_bot false
end
config.action_view.default_form_builder = 'ApplicationFormBuilder'
# ===== 以下を追加 =====
config.active_storage.variant_processor = :mini_magick
end
なぜかmodelでvariantを作成していたが正常に動かず
modelには下記variantを追記しています。
class Item < ApplicationRecord
# 1対1で関連つける宣言
has_one_attached :item_image do |attachable|
attachable.variant :thumb, resize_to_limit: [450, 300]
attachable.variant :max, resize_to_limit: [600,700]
end
end
ただviewでvariantを指定してもうまく動作せず。。。
※何かが間違ってる??
そのためshow.html.erbには画像に対して直接variant(resize: “600x700)を記載して対応
修正して表示の確認⇒ 成功
mini_magickを明示的にしてしたことでvariantメソッドを使っても画像が表示されました。
PS:レイアウトが崩れたので対処しました。
Bootstrapを導入して任意の場所に画像を埋め込んでいたところ
テンプレードではレイアウトが崩れていないのに自分のviewだと崩れていることが発覚しました。
レイアウト崩れはhtmlに原因があるのでviewのfileを確認してみると
<div class="col-md-6">
<%= image_tag @items.item_image.variant(resize: "600x700") %>
</div>
この状態でした。
テンプレートページを表示しF12で該当箇所のhtmlを確認してみるとimg classが抜けていることが発覚
<div class="col-md-6">
<img class="card-img-top mb-5 mb-md-0"
<%= image_tag @items.item_image.variant(resize: "600x700") %>
</div>
上記に修正することでレイアウト崩れの修正を行いました。
imgタグには閉じタグが不要なようです。
https://uruchikara.jp/how-to-use-img-tag/
逆らって閉じタグをいれようものなら、表示しているページに不自然に/>が表示されました。
以上、参考になれば幸いです。