LoginSignup
5
3

More than 3 years have passed since last update.

デフォルト画像を設定する方法

Last updated at Posted at 2021-04-19

はじめに

画像が登録されてない場合のデフォルト画像を設置する方法についてまとめていきます。
今回は、CarrierWave、asset pipelineを使用したやり方になります。

後半では、The asset "" is not present in the asset pipelineのエラーについて少し触れていきます。

CarrierWaveでデフォルト画像を定義

[app/uploaders/image_uploder.rb]
このように前もってデフォルト画像を設置するためのメソッドがコメントアウトして用意されているので、必要な部分を解除する。

# def default_url(*args)
  #   # For Rails 3.1+ asset pipeline compatibility:
    # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.jpeg"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

解除する場所。

 def default_url(*args)
    ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.jpeg"].compact.join('_'))
  end

"default.jpeg"の部分が、デフォルト画像のパスになります。
なので、デフォルトの画像のパスを統一してあげる作業が必要になります。

デフォルト画像の用意

実際に使用するデフォルトの画像をapp/assets/images/の配下に保存します。
先ほどもいったように保存するときは、"default.jpeg"の名前、形式を統一する必要があります。

ビューで呼び出し

 <%= image_tag '/assets/default.jpeg',:alt => 'ユーザーアイコン' %>

'default.jpeg'でもok
注意点としては、
・/assets/images/...とimagesを指定しないこと。
imagesを使用すると以下のような表示になる。
また、logではエラーが吐かれている。

ActionController::RoutingError (No route matches [GET] "/assets/images/default.jpeg"):

スクリーンショット 2021-04-19 22.29.55.png

まとめ

簡単ではありますが、デフォルト画像の設置方法についてまとめてみました。
少しでも参考になれば嬉しいです。

補足(The asset "" is not present in the asset pipelineエラーについて)

アセットパイプラインが存在しないと出てしまう原因。
結論
config/envitonments/production.rbファイルの

  config.assets.compile = true

falseをtrueにしてあげる
アセットアイプラインへのアクセスを許可するみたいなイメージだと思います。

参考資料

CarrierWaveでデフォルト画像の設定
アセットパイプライン、img_tagの使い方について記載されています。
Railsガイド
The asset "" is not present in the asset pipeline
GitHub/carrierwave
アセット使用しない方法も記載されています。

5
3
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
5
3