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 Mcleod <rails-mailing-l...@andreas-s.net>:
>> 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
-- 
Posted via http://www.ruby-forum.com/.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to