This is my attempt to use the FasterCSV plugin for rails. I am a very begin, begin again, programmer so it is my hope the some of this is true and others can point out whats wrong with the code:
Ok the problem:
To import a csv file (thats a comma delimited file) into a database (mysql for me) table.
Pretty simple task but if you don't know it all kinds of things crop up like:
How do I get the file in there?
How does it know where to map the data?
How do I not import the headers or blanks?
I have been emailing back and forth with a James Edward Gray II who wrote the FasterCSV in the first place and I hope that he can comment here so I can make this a working example for all to see.
Also I don't know how this is going to work on blogger but this is my easiest way to publish currently.
Subscribe to:
Post Comments (Atom)
4 comments:
Hi:
This could be an example of how to import data:
def import_csv
require 'fastercsv'
file=params[:document][:file]
FasterCSV.foreach(file, :row_sep => “\r”) do |row|
field1, field2, field3 = row
Record.create(:field1 => field1, :field2 => field2, :field3 => field3)
end
flash[:ok] = 'Data succesfully imported'
redirect_to home_url
end
and in the view:
form_for(:record, :url => import_csv_url, :multipart => true ) do
file_field 'document', 'file'
submit_tag 'Import data'
end
Thanks Jorge,
I have been noodling this for a while and will post (hopefully) my simple tutorial soon.... Thanks for the help.
Hi, I am really struggling with this. I have replicated your code but I don't get anything being saved to the database. I have replaced file with a known location and all is well.
it therefore seems that file_field is not passing the correct info.
My debug params output includes the following
document: !map:HashWithIndifferentAccess file: vendor.csv controller: vendor
I have started a github on this and it has better code you can get to it by going to www.github.com and searching on FasterCSV. I don't have all the code up there but will try to post my complete example soon. Also JEG has his stuff on github as well which may help you
Post a Comment