Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How show hide image in paperclip when no image present

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?

like image 609
neezer Avatar asked Nov 17 '08 21:11

neezer


3 Answers

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 %>
like image 198
Christoph Schiessl Avatar answered Nov 09 '22 16:11

Christoph Schiessl


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'
like image 53
Voldy Avatar answered Nov 09 '22 17:11

Voldy


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'
like image 31
neezer Avatar answered Nov 09 '22 18:11

neezer