How to check if a file exists in Ruby on Rails
Sometimes file uploads can go wrong; rather than risk your Rails app falling over, it makes sense to check if the file actually exists.
Your database might point to a filename in your public folder when there's no file there, to allow for this possibility you can do the following:
FileTest.exists?("#{@document.name}")
In the example above the object 'document' has a file_column field 'name'. Calling @document.name returns an absolute path for the upload.
The FileTest needs to be combined with a check to see if you are expecting a file to exist. So in this case it would be:
if @document.name && FileTest.exists?("#{@document.name}")
The reason for this is because you need to check that the filename is actually in the database before checking the file system.
FileTest is a ruby module that allows you to perform various tests on files, it's well worth checking out.
For my rails projects I've been using the file_column plugin to implement file uploads.
About
Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
1 comment made
FileTest.exists? is obsolete use FileTest.exist? (without s).
Thanks
Got something to say?