Reputation: 1080
What's the best way to check whether the user selected a file for upload in the controller? At the moment I have -
def create
if @object.foo.file.exists?
do something to object
end
if @object.save etc.
But this returns 'undefined method `exists?' for nil:NilClass'
In the console, 'exists?' works where it returns true, but throws the error when it should return false. I've tried 'object.save' before querying 'exists?' but it doesn't fix it.
Upvotes: 1
Views: 1463
Reputation: 167
The object in the params hash is an instance of a subclass of IO. Depending on the size of the uploaded file it may in fact be a StringIO or an instance of File backed by a temporary file. In both cases the object will have an original_filename attribute containing the name the file had on the user's computer and a content_type attribute containing the MIME type of the uploaded file.
If the user has not selected a file the corresponding parameter will be an empty string.
So you could start by checking if your param is an empty string.
Hope this helps.
Upvotes: 1