LoginSignup
3
1

More than 5 years have passed since last update.

paperclipのhas_attached_fileのオプションで画像のデフォルト値を設定する

Posted at

はじめに

今回は、画像のデフォルト値を設定することで、画像がアップロードされなかった際に任意の画像を表示させます。

モデルファイル内

以下通常の記述内容

user.rb
#paperclip
has_attached_file :avatar,style: { medium: '300x300', thumb: '100x100' }
validate_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/

default_urlオプションを使用することで、デフォルト値の設定をすることができます。

user.rb
#paperclip
has_attached_file :avatar,style: { medium: '300x300', thumb: '100x100' }, default_url: '/images/no_image.png'
validate_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/

として、デフォルト値に設定する画像をapp/public/images/no_image.pngに置きます。これで完了です。
注意:assetsフォルダ内のimagesの中に画像を置いてもうまく適用されませんでした。この理由はわかりません。詳しい方いましたらコメントしていただくと大変助かります。

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