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?

4

8 回答 8

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 %>
于 2008-11-17T23:22:25.700 回答
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'
于 2010-11-16T18:36:59.340 回答
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'
于 2008-11-17T21:24:17.670 回答
18

Few bytes less:

<% if @agent.avatar? %>
  <%= image_tag @agent.avatar.url(:normal) %>
<% else %>
  No attachment available!
<% end %>
于 2010-03-02T14:15:14.020 回答
3

It is better to use :default_url rather than conditions.

于 2010-11-18T09:44:07.817 回答
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 %>
于 2014-08-20T10:02:05.627 回答
0

You can use this

user.photo.exists?(:medium).
于 2014-12-19T16:35:59.863 回答
0

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

<% if @post.image.exists? %>
<%= image_tag @post.image.url %>
<% end %>
于 2017-03-14T04:22:22.697 回答