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.
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.
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.
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
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