user852974
user852974

Reputation: 2282

Only display a user-uploaded photo if it exists in rails

<%= image_tag message.photo.url(:small) %>

I have paperclip installed and the above code displays an image that the user uploads which has been resized to :small (in this case 40x40px. How can I get my page to display this image only if it exists? Currently if the message includes a photo that photo is displayed but all other messages show broken image links. Thanks

Upvotes: 2

Views: 685

Answers (2)

Yardboy
Yardboy

Reputation: 2805

Paperclip adds the name of the attachment suffixed with a "?" to the attached model as a helper method to allow you to see whether or not there is an attachment. In your case, the helper method would be photo? on the message class. You could use it with the tertiary operator in this manner:

<%= message.photo? ? image_tag message.photo.url(:small) : "" %>

Or, if you'd like to show a default no-image image when there is no image...

<%= image_tag message.photo? ? message.photo.url(:small) : url_to_no-image_image %>

Upvotes: 2

Jesse Jashinsky
Jesse Jashinsky

Reputation: 10663

It's been a while since I've used rails, but wouldn't it suffice to just put in an if statement?

Upvotes: 1

Related Questions