简体   繁体   中英

Paperclip gives error when image is not uploaded

Paperclip works fine when I upload an image and then display it with:

<%= image_tag @post.photo.url(:medium) %>

The problem is, if an image wasn't uploaded, I get this error:

NoMethodError in Posts#show

Showing /Users/me/RubymineProjects/level_60/app/views/posts/show.html.erb where line #16 raised:

undefined method `[]' for nil:NilClass

I try to check and see if the image exists with <% if @post.photo %> or <% if @post.photo != '' %> . However, both of those always return true even when there's no image uploaded.

How do I display an image through paperclip only if it exists?

The problem is that checking for @post.photo returns something that does not equal false , whatever it is. To debug this, simply print a @post.photo.inspect in your controller or view into your logfile.

Seeing that your comment already says it's a Paperclip::Attachment object, good candidates for checking would be @post.photo.size > 0 or @post.photo.errors.empty? , or (probably best) @phost.photo.file? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM