How show hide image in paperclip when no image present
Asked Answered
A

8

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?

Adermin answered 17/11, 2008 at 21:13 Comment(0)
V
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 %>
Ventose answered 17/11, 2008 at 23:22 Comment(3)
sweet, used paperclip for a long time and didn't know about this ;)Romine
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.Frizzly
Very nice! This is an easy quick fix.Norvun
K
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'
Klayman answered 16/11, 2010 at 18:36 Comment(1)
i did a variation with default_url being '/images/:style/missing_modelname.png' for multiple models that have attachmentsGarget
A
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'
Adermin answered 17/11, 2008 at 21:24 Comment(0)
L
18

Few bytes less:

<% if @agent.avatar? %>
  <%= image_tag @agent.avatar.url(:normal) %>
<% else %>
  No attachment available!
<% end %>
Lauricelaurie answered 2/3, 2010 at 14:15 Comment(0)
A
3

It is better to use :default_url rather than conditions.

Antispasmodic answered 18/11, 2010 at 9:44 Comment(0)
E
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 %>
Engelhart answered 20/8, 2014 at 10:2 Comment(0)
K
0

You can use this

user.photo.exists?(:medium).
Kigali answered 19/12, 2014 at 16:35 Comment(0)
S
0

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

<% if @post.image.exists? %>
<%= image_tag @post.image.url %>
<% end %>
Silvey answered 14/3, 2017 at 4:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.