Hi,
I followed the instruction on Agile Development book to upload files
(attached below)
I want to check that the user entered a name for the file and that the
size of the file is not greater than 1 megabyte. However, the
“validates_for_presence” and “validates_size_of” are not putting any
error message on the screen for the user and I only get Sql and
application error.
appreciate any help.
Thanks,
-Albert
Controller:
def upload_file
@document = Document.new
…
end
def save_file
@document = Document.new(params[:document])
if @document.save
flash[:notice] = “file has been successfully uploaded”
redirect_to (params[:referer] || :back)
else
render(:action => :upload_file)
end
end
Model:
class Document < ActiveRecord::Base
validates_size_of :data, :maximum => 1.megabyte
validates_presence_of :name
def document=(document_field)
self.name = base_part_of(document_field.original_filename)
self.content_type = document_field.content_type.chomp
self.data = document_field.read
end
def base_part_of(file_name)
name = File.basename(file_name)
name.gsub(/[^\w._-]/, ‘’ )
end
end
View:
<%= error_messages_for(“document” ) %>
<%= form_tag({:action => ‘save_file’, :member_study => @member_study},
:multipart => true) %>
<%= file_field(“document” , “document”, “size” => 66) %>
<%= text_area(“document” , “comment”, “cols” => 50 , “rows” => 5 ) %>
<%= submit_tag(“Upload file” ) %>
<%= hidden_field_tag “referer”, nil, :value =>
request.env[“HTTP_REFERER”] %>
<%= end_form_tag %>