Hello all,
I’m trying to validate a uploaded file extension. I’m not using any
special plugin other that fastercsv.
When I try to upload an incorrect file (say a “.doc”), I get this error
message…
“Error adding logs. (Unquoted fields do not allow \r or \n (line 2).).
Please try again.”
Below is my model.
-model-
class Import < ActiveRecord::Base
validates_format_of :import, :with => /^.+.(csv)$/,
:message => ‘A .csv file is required.’
end
It should work but it doesn’t.
Any help with this is greatly appreciated.
Thank you.
JohnM
I think you try to parse the csv before saving the model to the db.
Thats when validations would be run. You should catch any FasterCSV
Exceptions and give a proper error message in the controller.
2009/10/8, John M. [email protected]:
Below is my model.
Thank you.
JohnM
Posted via http://www.ruby-forum.com/.
–
Von meinen Mobilgerät aus gesendet
+1 on Mike’s suggestion - otherwise, you’ll get users RENAMING
their .doc file to end with .csv and uploading it over and over…
–Matt J.
On Oct 8, 11:47 am, John M. [email protected]
mike wrote:
I think you try to parse the csv before saving the model to the db.
Thats when validations would be run. You should catch any FasterCSV
Exceptions and give a proper error message in the controller.
2009/10/8, John M. [email protected]:
Below is my model.
Thank you.
JohnM
Posted via http://www.ruby-forum.com/.
–
Von meinen Mobilger�t aus gesendet
Thanks for the advice.
I checked the controller and sure enough there’s a ‘rescue => exception’
I parsed out the file extension then did a simple conditional for ‘csv’
Here’s my controller for anyone that falls into the same quagmire.
-
Controller -
def process_csv
file = params[:import][:file]
rowcount = 0
Import.transaction do
FasterCSV.parse(file,
:headers => true,
:header_converters => :symbol ) do |row|
Import.create!(row.to_hash)
rowcount += 1
end
end
if successful then display, then redirect to index page
flash[:notice] = “Successfully added #{rowcount} project(s).”
redirect_to :action => :index
rescue => exception
file_name = params[:import][‘file’].original_filename
file_parts = params[:import][‘file’].original_filename.split(‘.’)
ext = file_parts[1]
if ext != ‘csv’
error = “CSV file is required”
else
error = ERB::Util.h(exception.to_s) # get the error and HTML
escape it
end
If an exception in thrown, the transaction rolls back and we end
up in this
# rescue block
flash[:error] = "Error adding projects to Import table. (#{error}).
Please try again. "
redirect_to :action => :new
end
Thanks again.
JohnM