0

Right now, each time I need to display a user's avatar, I have if statements that check whether they uploaded an avatar or not. I know it's definitely not DRY if I have these statements littered through my html.

So, what's the best way to find out which image to display?

Edit: I'm using Carrierwave (Paperclip didn't work for me for some reason)

Raymond R
  • 1,350
  • 3
  • 12
  • 19

4 Answers4

1

Try using helper methods.That should solve your worries. Your helper would be like

def check_avatar(user)
     if user.image.nil?
       # return default image
    else
       #return user avatar
    end
end


The usage in your views would be
check_avatar(user)

sureshprasanna70
  • 1,043
  • 1
  • 10
  • 27
1

You can do that with Paperclip

You can add the following to your User-Model (app/models/user.rb):

has_attached_file :avatar, default_url: "avatar.png"

You have to place your Image into

app/assets/images/
Marco Roth
  • 184
  • 4
  • 11
1

It is documented in CarrierWave's repo.

https://github.com/carrierwaveuploader/carrierwave#providing-a-default-url

Providing a default URL

In many cases, especially when working with images, it might be a good idea to provide a default url, a fallback in case no file has been uploaded. You can do this easily by overriding the default_url method in your uploader:

class MyUploader < CarrierWave::Uploader::Base
  def default_url(*args)
    "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  end
end

Or if you are using the Rails asset pipeline:

class MyUploader < CarrierWave::Uploader::Base
  def default_url(*args)
    ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  end
end
Community
  • 1
  • 1
Harsh Gupta
  • 4,348
  • 2
  • 25
  • 30
1

If your avatar URL is stored USER.AVATAR in your DB, then:

class User
  DEFAULT_AVATAR = "xyz"
  def avatar
    read_attribute('avatar') || DEFAULT_AVATAR
  end
end
AnoE
  • 8,048
  • 1
  • 21
  • 36