39

How can I prevent the image tag that calls the associated image from displaying if no image is associated with the record?

<%= image_tag @agent.avatar.url %>

...gives me the text "Missing" if there is no image associated with that agent. I want to test to see there is an image available first, then render the above tag if the test returns true.

Better yet, is there anyway for me to specify a default image if no image is specifically provided?

carbonr
  • 6,049
  • 5
  • 46
  • 73
neezer
  • 19,720
  • 33
  • 121
  • 220

8 Answers8

60

I use the following to find wether a model has an associated attachment:

<% if @agent.avatar.file? %>
  <%= image_tag @agent.avatar.url(:normal) %>
<% else %>
  No attachment available!
<% end %>
Christoph Schiessl
  • 6,818
  • 4
  • 33
  • 45
  • sweet, used paperclip for a long time and didn't know about this ;) – thenengah Jan 16 '11 at 07:19
  • Although the other answer is a better general-purpose solution, I'm using this one because I want to rearrange the layout if something doesn't have an attached image, not just display a placeholder image. – Alfo Mar 09 '13 at 14:13
  • Very nice! This is an easy quick fix. – Jordan May 20 '14 at 02:58
53

If avatar has multiple sizes:

has_attached_file :avatar, 
                  :styles => {:small => '30x30#', :large => '100x100#'}, 
                  :default_url => '/images/missing_:style.png'

for Rails 3:

has_attached_file :avatar, 
                  :styles => {:small => '30x30#', :large => '100x100#'}, 
                  :default_url => '/assets/images/missing_:style.png'
Hauleth
  • 22,873
  • 4
  • 61
  • 112
Voldy
  • 12,829
  • 8
  • 51
  • 67
  • 3
    i did a variation with default_url being '/images/:style/missing_modelname.png' for multiple models that have attachments – corroded May 16 '11 at 07:17
31

Okay, so I got one part of it.

Specifying a default image happens in the model

has_attached_file :avatar, :default_url => '/images/brokers/agents/anonymous_icon.jpg'
neezer
  • 19,720
  • 33
  • 121
  • 220
18

Few bytes less:

<% if @agent.avatar? %>
  <%= image_tag @agent.avatar.url(:normal) %>
<% else %>
  No attachment available!
<% end %>
tig
  • 25,841
  • 10
  • 64
  • 96
3

It is better to use :default_url rather than conditions.

ashisrai_
  • 6,438
  • 2
  • 26
  • 42
1

If a default_url has been specified in the model you can use the method present? to check if the url is the default or an uploaded one.

<% if @agent.avatar.present? %>
  <%= image_tag @agent.avatar.url(:normal) %>
<% else %>
  No attachment available!
<% end %>
0

You can use this

user.photo.exists?(:medium).
stopanko
  • 306
  • 3
  • 7
0

I also had the same problem before, but solved it by using:

<% if @post.image.exists? %>
<%= image_tag @post.image.url %>
<% end %>
g00glen00b
  • 41,995
  • 13
  • 95
  • 133
Nami
  • 25
  • 6