15
24

More than 3 years have passed since last update.

Active Storageでデフォルト画像を設定する

Last updated at Posted at 2020-03-12

CarrierWaveでデフォルト画像を設定する記事はよく見かけるが、Active Storageの日本語の記事は見かけなかったのでメモ。
オブジェクト作成時に、デフォルトの画像を紐付ける。

方法

  • assets/images に適当な画像を保存。
  • デフォルト画像を設定したいクラスのファイルに以下を追加。
before_create :default_image

def default_image
  if !self.image.attached?
    self.image.attach(io: File.open(Rails.root.join('app', 'assets', 'images', 'event_default.png')), filename: 'default-image.png', content_type: 'image/png')
  end
end

これでオブジェクト作成時にデフォルト画像を設定することができた。

今まではビューファイルにif文で表示を変えるコードを書いていたが、このようにスマートにかけるようになった。

#変更前
<% if event.image.attaced? %>
 <%= image_tag event.image %>
<% else %>
 <%= image_tag 'dehault.img' %>
<% end %>

#変更後
<%= image_tag event.image %>
15
24
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
15
24