Forum: Ruby on Rails Validation in File Upload

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2d2e623b169075649a21a5108d17a4b7?d=identicon&s=25 Justin (Guest)
on 2006-05-02 23:24
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--
<h3>Add a New Newsletter</h3>
<%= form_tag({:action=>'add_newsletter'}, :multipart=>true) %>
<table>
<tr>
  <td>Title</td>
  <td><%=text_field(:newsletter,:name)%></td>
</tr>
<tr>
  <td>Publication Date</td>
  <td><%=date_select(:newsletter,:pubDate,:order=>[:month,:day,:year])%></td>
</tr>
<tr>
  <td>PDF File</td>
  <td><%=file_field(:newsletter,:newsletter)%></td>
</tr>
<tr>
  <td valign="top">Description</td>
  <td><%=text_area(:newsletter,:summary)%></td>
</tr>
<tr>
  <td colspan="2" align="right"><%=submit_tag("Add Newsletter")%></td>
  </tr>
</table>
<%= end_form_tag %>
This topic is locked and can not be replied to.