How to know if an image has been uploaded or not? - Paperclip
Asked Answered
B

5

8

do you know if is there a method to know if the image has been uploaded?

I mean, i have a Foo_Class, and this class can have an attached image, but its presence is not necessary. Is there a way to know if a particular instance of that class have the image or not?

Thanks!

Belinda answered 8/4, 2011 at 10:31 Comment(0)
K
8

When you added Paperclip to your model you added paperclip specific rows, mine are

cover_file_name
cover_content_type
cover_file_size
cover_updated_at

Then I check whether it is nil or not

 Foo_Class.cover_file_name.nil? 
Klotz answered 8/4, 2011 at 12:41 Comment(0)
V
11

If foo.image? returns true, then file uploaded.

Verruca answered 27/5, 2011 at 14:7 Comment(4)
It's now foo.image.exists?Whoso
what if you have set :default_url => 'missing.png' ? would that be considered as foo.image.exists?Extremist
the answer is: no, it will return falseExtremist
This technique goes to the server and checks if the file is there. The voted up technique checks if it as been processed and a URL has been generated. Upvoted solution saves lookup (which might be on S3) but it does not check if the file actually exists on the image server (which you may or may not want to check.Wynnie
K
8

When you added Paperclip to your model you added paperclip specific rows, mine are

cover_file_name
cover_content_type
cover_file_size
cover_updated_at

Then I check whether it is nil or not

 Foo_Class.cover_file_name.nil? 
Klotz answered 8/4, 2011 at 12:41 Comment(0)
W
6

I think that the proper solution is to use the file? method.

foo.image.file?

http://rdoc.info/github/thoughtbot/paperclip/Paperclip/Attachment#file%3F-instance_method

using exists? will do a request to the server to check if the file is there, which can be quite slow, especially if it's on a different server or on S3.

using foo.image_file_name.nil? is probably the same as file? under the covers, but ou don't want to dependant on the implementation of paperclip, which could someday change.

Wynnie answered 1/10, 2014 at 15:46 Comment(0)
R
1

If this is in my model

has_attached_file :avatar, :styles => {:logo => "230x50>", :card_image => "180x50>"}

You can check if the image is uploaded for a user i.e @user

<%= @user.avatar.exists? %>

This will return boolean value.

Rodenhouse answered 13/4, 2015 at 13:37 Comment(1)
If your file is on S3, this will trigger a request to S3.Conflux
L
0

Suppose you want to check the presence of attachment(image) for the 1st row in Foo model:

image_present = Foo.first.image?

This returns true if the attachment is present.

Luftwaffe answered 18/8, 2016 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.