How to validate presence of an uploaded file in rails?
- by brad
I'm playing around creating a rails file uploader and have struck a problem that should have an obvious solution. How do I check that a file has been selected in my form and uploaded?
Here is my new.html.erb view
<h2>Upload File</h2>
<% form_for(@upload_file, :url => {:action => 'save'}, :html => {:multipart => true}) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :file -%>
<%= f.file_field :upload -%>
</p>
<p>
<%= f.label :description %>
<%= f.text_field :description %>
</p>
<p>
<%= f.label :file_type %>
<%= f.select :file_type, ["XML Data"] %>
</p>
<p><%= f.submit 'Upload File' %></p>
<% end %>
and here is my upload_file.rb model
class UploadFile < ActiveRecord::Base
validates_presence_of :description
validates_presence_of :file_type
validates_presence_of :upload
def upload=(upload_file_field)
self.name = "#{Time.now.strftime("%Y%m%d%H%M%S")}_#{upload_file_field.original_filename}"
File.open("#{RAILS_ROOT}/public/upload/#{self.name}", "wb") { |f| f.write(upload_file_field.read) }
end
end
If I use this as shown here, the validation validates_presence_of :upload always fails and I am returned to my form with an error message.
I'd be very grateful if someone could explain how to do this validation correctly, and I'd be even more grateful if they could explain why it works.
Thanks.