LoginSignup
25
25

More than 3 years have passed since last update.

CarrierWaveでデフォルト画像の設定

Last updated at Posted at 2020-02-16

CarrierWaveでユーザーアイコンの実装をしていたのですが、デフォルト画像の表示で少し躓いてしまったのでメモしておきます。

前提

  • CarrierWaveは導入済み
  • 登録した画像表示はできる

image_uploader.rbの設定

CarrierWaveを入れたときに

$ rails g uploader image

をしたらimage_uploader.rbというファイルが生成されます。

このファイルを以下のようにいじってください。

image_uploader.rb
#アップロードした画像の表示
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

#デフォルト画像の設定
  # Provide a default URL as a default if there hasn't been a file uploaded:
  def default_url(*args)
  #   For Rails 3.1+ asset pipeline compatibility:
    ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  end

これで登録時にファイル選択をしなかった場合、デフォルト画像をimageとして渡す準備ができました。

assets/images配下に画像を設置

assets/images配下にデフォルト画像を設置してください。
画像名はこの場合「default.png」にしときましょう。

Viewの設定

Viewに、if文でユーザーのimageがある場合とない場合で表示が変わるように設定してあげましょう。

以下は例です。

_show.html.erb
<% if post.user.image? %>
  <img src='<%= post.user.image %>' class="icon" alt="ユーザーアイコン">
<% else %>
  <image src="/assets/default.png" class="icon" alt="ユーザーアイコン" %>
<% end %>

まとめ

CarrierWaveさんは非常に便利なのですが、デフォルト画像設置に関しては画像パスとして渡っているので、dbを調べてもnullとしか表示されず焦ってしまうというパターンがよくあるようです。

よく使う機能だとは思いますので、誰かの助けになれば幸いです。

ではでは。

25
25
1

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
25
25