Skip to content

Instantly share code, notes, and snippets.

@kinopyo
Created March 28, 2012 08:52
Show Gist options
  • Save kinopyo/2224867 to your computer and use it in GitHub Desktop.
Save kinopyo/2224867 to your computer and use it in GitHub Desktop.
Check whether a Paperclip attachment exists

Check whether a Paperclip attachment exists

Don’t simply test for the presence of the magic Paperclip attribute, it will return a paperclip Attachment object and thus always be true:

- if user.photo.present? # always true
  = image_tag(user.photo.url)

Use #photo? instead:

- if user.photo?
  = image_tag(user.photo.url)
@dfrancisc
Copy link

But what if I want to know if a user.photo.url(:medium) exists ?

@chamnap
Copy link

chamnap commented Jul 30, 2014

do it this way user.photo.exists?(:medium).

@zzz6519003
Copy link

thx!

@icem
Copy link

icem commented Apr 20, 2015

- if user.photo.present? # always true
  = image_tag(user.photo.url)

That's not true! #present? checks if attachment was assigned and #exists? checks if file is on storage(S3 or whatever). Here is attachment code from paperclip:

    # Returns true if a file has been assigned.
    def file?
      !original_filename.blank?
    end

    alias :present? :file?

    def blank?
      not present?
    end
      def exists?(style = default_style)
        if original_filename
          s3_object(style).exists?
        else
          false
        end
      rescue AWS::Errors::Base => e
        false
      end

That means #present? is much faster that #exists? and you rarely need second unless you have problems with your storage.

@brendon
Copy link

brendon commented Mar 26, 2017

user.photo.exists? seems to actually be user.photo.exists?(:original). For some reason I didn't have an 'original' for some of my older attachments and this caused the logic to fail even though the thumbnails etc... were there.

@atibus15
Copy link

atibus15 commented May 8, 2017

just use the file_name column to check.
def thumbnail_path
thumbnail_file_name.present? ? thumbnail : nil
end

@codertcet111
Copy link

user.photo.exists? Always return me 'false', for both the cases.
It is showing me some message as, 'Digest::Digest is deprecated; use Digest', and then giving me 'false'.

@toadkicker
Copy link

user.photo_file_name.blank? is how i do it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment