Friday, October 30, 2009

[Rails] Re: updating model while reading CSV

Hey John,

Last week I wrote this code to allow you to easily create models/
records using FasterCSV... it doesn't directly answer your question,
but it might help or at least give you some ideas:
http://pastie.org/676681

If it looks this would be useful to you or others I can post it on
github; I also have a test suite for it. - pat

On Oct 29, 12:52 pm, John Mcleod <rails-mailing-l...@andreas-s.net>
wrote:
> Hello all,
> I was wondering how to update an existing table column when reading in a
> CSV? I'm using FasterCSV and my controller method is this...
>
> - Import Controller -
> def process_csv
>
>     # set file name
>     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
>
> As I read the CSV file, I wish to update a column in the model, mainly
> "ProjectType" as the record is being created.
>
> The CSV file does not have this information and there's no possibility
> that it'll ever have it.
>
> Thank you for any help.
>
> JohnM
> --
> Posted viahttp://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+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate