# File\_field throws exception when field is left blank

**URL:** <https://www.ruby-forum.com/t/file-field-throws-exception-when-field-is-left-blank/137403>\
**Category:** Rails\
**Created:** [May 12, 2008, 9:58pm UTC](https://www.ruby-forum.com/t/file-field-throws-exception-when-field-is-left-blank/137403 "2008-05-12T21:58:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dino\_d](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b5ac83/32.png) [@dino\_d](https://www.ruby-forum.com/u/dino_d)\
**Post date:** [May 12, 2008, 9:58pm UTC](https://www.ruby-forum.com/t/file-field-throws-exception-when-field-is-left-blank/137403/1 "2008-05-12T21:58:10Z")

</div>

hi -

I’m adapting a file upload from the Agile book. I have two models,  
Challenge and MediaFile. The form looks like this:

\<%form\_for :challenge, :url =\> {:action  
=\>:create}, :html=\>{:multipart=\>true} do |f|%\>  
\<%fields\_for :media\_file do |m|%\>  
Please select a media file: \<%=m.file\_field :uploaded\_data%\>  
…

The MediaFile model has a method defined ‘uploaded\_data’

def uploaded\_data=(picture\_field)  
name = base\_part\_of(picture\_field.original\_filename)  
content\_type = picture\_field.content\_type.chomp  
data = picture\_field.read  
end

This works fine, unless the user doesn’t select a file for upload. In  
this case, picture\_field is a blank string, and the model has no  
attribute original\_filename, etc. So the exception is:

undefined local variable or method `original\_filename’ for #\<MediaFile:  
0x574b3c8\>

The question is, how do I detect when a user hasn’t selected a file  
for upload, and gracefully add an error to the errors collection? I  
wonder if this has something to do with having two models? Like I  
said, it works just fine when the user selects a file.

Thanks for any help,  
Dino

---

<div class="post-metadata">

**Author:** ![dino\_d](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b5ac83/32.png) [@dino\_d](https://www.ruby-forum.com/u/dino_d)\
**Post date:** [May 13, 2008, 5:06am UTC](https://www.ruby-forum.com/t/file-field-throws-exception-when-field-is-left-blank/137403/2 "2008-05-13T05:06:59Z")

</div>

On 5/12/08, dino d. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> The question is, how do I detect when a user hasn’t selected a file  
> for upload, and gracefully add an error to the errors collection?

Rescue the exception and add an error to the model.

begin

# put whatever explodes here

rescue  
@foo.errors.add( :file, ‘oops’ )  
end

[http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut\_exceptions.html](http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html)

[http://api.rubyonrails.com/classes/ActiveResource/Errors.html#M000801](http://api.rubyonrails.com/classes/ActiveResource/Errors.html#M000801)

–  
Greg D.  
[http://destiney.com/](http://destiney.com/)
