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 --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
Greg Donald
2008-May-13 03:06 UTC
Re: file_field throws exception when field is left blank
On 5/12/08, dino d. <dinodorroco-/E1597aS9LQAvxtiuMwx3w@public.gmane.org> 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://api.rubyonrails.com/classes/ActiveResource/Errors.html#M000801 -- Greg Donald http://destiney.com/ --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---