I am using the csv-mapper gem to import a csv file. When I use the example code on in the README (http://github.com/pillowfactory/csv-mapper) in script/console it works great. However, when I create a web form and use that to upload a csv file I get the error "No such file or directory - test.csv
These are the parameters: Parameters:
{"dump"=>{"file"=>#}, "commit"=>"Submit", "authenticity_token"=>"Hb+XDPUGyZQqB5H2vZnhlfXpEE9bAE16kAjTT34uQ3U="}
Here is what I have for my code in the control开发者_如何学JAVAler:
def csv_import
results = CsvMapper.import(params[:dump][:file].original_filename) do
map_to Sale # Map to the Sale ActiveRecord class instead of the default Struct.
after_row lambda{|row, sale| sale.save } # Call this lambda and save each record after it's parsed.
start_at_row 1
[start_date, country]
end
flash[:notice] = "Successfully uploaded file"
end
This is a little late, but you should also note that CsvMapper#import takes any IO when you pass it the :type => :io option.
results = CsvMapper.import(params[:dump][:file], :type => :io) do
...
end
This would allow you to skip the step of saving the file prior to importing.
The error is expected because params[:dump][:file].original_filename
only returns the file name of the uploaded CSV. The uploaded CSV should be saved to the file system first. Pass the path to the saved CSV file to CsvMapper#import
method then it should work.
See here for how to save uploaded files.
精彩评论