I am using Paperclip to handle profile photo uploads in my app. They upload well and resize to the specifications in my model. However, if a User's profile :photo is nil, no matter what I try I can't change the default. Here's the code I want to use:
<% if @profile.photo.nil? %>
<%= image_tag "public/images/example.jpg", :html => { :id => "noUserProfile" } %>
<% else %>
<%= image_tag @profile.photo.url(:normal) %>
<% end %>
I've tried "../public/images/example.jpg" and that doesn't work either even though I have "example.jpg" in my public images folder. When I copy image address in my view, I get:
http://localhost:3000/photos/normal/missing.png
I added those folders to my app and put a missing.png file in there and nothing. If I go to the above URL I get No route matches "/photos/normal/missing.png"
Does anyone have any ideas as to what's going on?
has_attached_file in Profile model:
has_attached_file :photo,
:styles => {
:normal => "153x220#",
:small => "75x108#" }
add_attachment_photo_to_profile migration:
class AddAttachmentPhotoToProfile < ActiveRecord::Migration
def self.up
add_column :profiles, :photo_file_name, :string
add_column :profiles, :photo_content_type, :string
add_column :profiles, :photo_file_size, :integer
add_column :profiles, :photo_updated_at, :datetime
end
def self.down
remove_column :profiles, :photo_file_name
remove_column :profiles, :photo_content_type
remove_column :profiles, :photo_file_size
remove_column :profiles, :photo_updated_at
end
end
This is the HTML that's rendered for when the :photo
exists:
<div class="userSnapshot">
<div class="smFrame">
<div class="smUserPhoto">
<img alt="8217_667699353137_15600054_38423586_7789442_n" src="/system/photos/1/small/8217_667699353137_15600054_38423586_7789442_n.jpg?1316052048" />
</div>
</div>
<div class="findinfo">
<p><a href="/profiles/1">Name</a></p>
</div>
</div>
This is the HTML that's rendered for when the :photo
is nil:
<div class="userSnapshot">
<div class="smFrame">
<div class="smUserPhoto">
<img alt="Missing" src="/photos/small/missing.png" />
</div>
</div>
<div class="findinfo">
<p><a href="/profiles/2">Name</a></p>
</div>
</div>
I think you want the exists?
method.
if @profile.photo.exists?
@profile.photo.nil?
will always be false
because it returns the default image when it's missing.
NOTE: This checks if the really file exists, and can be very slow if you host your images on a CDN.
As a work around you might be able to just check if the database thinks there is a file:
if @profile.photo_file_name.present?
Check out the :default_url
option in the rdocs, that's why it's rendering as it is. Paperclip handles the cases when there's no attached file.
You can set the default to something different and avoid the extra work in your template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With