paperclip check is have attachment

up vote5down votefavorite
2

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?

link|flag

add comment

up vote5down voteaccepted

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 %>
link|flag
add comment
up vote9down vote

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'
link|flag
add comment
up vote7down vote

Few bytes less:

<% if @agent.avatar? %>
 
<%= image_tag @agent.avatar.url(:normal) %>
<% else %>
  No attachment available!
<% end %>
link|flag
 
原文地址:https://www.cnblogs.com/lexus/p/1869301.html