6

I'm using Rails 3 paperclip and allow users to upload attachments to the attachment model.

If the file is an image, the app generates image previews. If the file is not, it only uploads the file (no image previews).

Now I would like to display a list of all the attachments in the DB. So I use attachment.attachment(:large) and that works fine for image attachments, but errors (obviously) for non-image attachments.

What's a good way to check if it's an image attachment or not? If not, I'd like to display a standard static image. Any suggestions? thanks

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

4 Answers4

7

This is what I did in my view:

<% if !(@attachment.attachment.content_type =~ /^image/).nil? %>
<%= image_tag @attachment.attachment.url(:small) %>
<%end%>

This assumes that your model is attachment, and my file, I so called attachment.

So you could do something like:

<% if !(@attachment.attachment.content_type =~ /^image/).nil? %>
<%= image_tag @attachment.attachment.url(:small) %>
<%else%>
<%= image_tag "/path/to/image/default.png" %>
<%end%>
Travis Pessetto
  • 3,260
  • 4
  • 27
  • 55
3

Check attachment.attachment.attachment_content_type

For example, it might be: "image/jpeg"

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
TK-421
  • 10,598
  • 3
  • 38
  • 34
0

Maybe you could use default_url option? That would be shown if the real thumbnail doesn't exist.

http://www.suffix.be/blog/default-image-paperclp

Heikki
  • 15,329
  • 2
  • 54
  • 49
  • Unfortunately I don't think this works. It works if there's no attachment at all (ie: the attachment property in the model is set to nil) but didn't detect a missing thumbnail file for me. (FWIW I'm on paperclip 2.3.1). If there's something I'm possibly doing wrong, I'd love to know about it! – Craig Walker Feb 03 '11 at 23:07
0

You can create a migration that adds a attachment_content_type field of type string to your attachment table. When you create an attachment, paperclip stores the type of the file in that field. You can then check if the file type is something like "image/jpeg".

Roy
  • 43,878
  • 2
  • 26
  • 26