Validation in File Upload


#1

I have an app whose admin allows users to upload PDFs to populate a
“newsletter” section.

I’m having trouble getting validation to work properly.

I want to be sure that a name, description & file are specified in the
form.

The app seems to catch the error and won’t write a row to the DB but it
will create a file sized 0KB in the upload folder and it won’t show the
error messages for that model. (using error_messages_for…)

CODE IS BELOW…Thanks

—CONTROLER----

def add_newsletter
@newsletter = Newsletter.new(params[:newsletter])
if @newsletter.save
flash[:notice] = “Added a newsletter: #{@newsletter.name}”
redirect_to(:action=>‘newsletter’)
end
end

----MODEL----
class Newsletter < ActiveRecord::Base
validates_presence_of :name, :summary, :filename

def newsletter=(newsletter_field)
self.filename = sanitize_filename(newsletter_field.original_filename)
self.filename = Time.now.strftime("%H%M%S")+self.filename
#self.data = element_field.read
File.open("#{RAILS_ROOT}/public/newsletters/#{self.filename}",“wb”) {
|f| f.write(newsletter_field.read)}
end

private
def sanitize_filename(value)
    just_filename = value.gsub(/^.*(\\|\/)/, '')
    @filename = just_filename.gsub(/[^\w\.\-]/,'_')
end

end

–VIEW–

Add a New Newsletter

<%= form_tag({:action=>'add_newsletter'}, :multipart=>true) %>
Title <%=text_field(:newsletter,:name)%>
Publication Date <%=date_select(:newsletter,:pubDate,:order=>[:month,:day,:year])%>
PDF File <%=file_field(:newsletter,:newsletter)%>
Description <%=text_area(:newsletter,:summary)%>
<%=submit_tag("Add Newsletter")%>
<%= end_form_tag %>