9

I'm trying to import CSV data to my mysql DB but I'm running into an error when I try to upload the file :

no implicit conversion of ActionDispatch::Http::UploadedFile into String

This is what a line in the CSV file looks like :

751,"01/17/2015","11:17:32","60","TDFSRDSK","2","10","-1","0","3","","26","3","","","1","0"

here is the code for the import, in product.rb

def self.import(file)
  CSV.foreach(file) do |row|
    id, jour, heure, valeur, app, a, b, c, d, e, f, g, h, i, j, k, l = row
    userid = current_user.id
    product = Product.create(date: jour, valeur: valeur,user_id: userid)
  end
end

in product_controller.rb

def import
 Product.import(params[:file])
 redirect_to_root_url, notice "Products imported"
end

in the index :

<%= form_tag import_products_path, multipart: true do %>
 <%= file_field_tag :file %>
 <%= submit_tag "Import" %>
<% end %>

and in routes.rb I have:

resources :products do
 collection {post :import}
end

2 Answers 2

20

Try give params[:file].path in argument. Like this,

Product.import(params[:file].path)

Checkout this.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks I managed to get rid of the error messages with your solution, now it seems to work but no data are added to the SQL table
At creation, try by using Product.create!(..) . So it will trows exception if any.
Thanks, I guess my data mapping to the sql has a problem because they all show as NULL and none were created because I have a "validates" on the field in my model. I'll try to find the right way to map ip
3

You need to do as :

CSV.foreach(file.path)

Your file is holding an instance of ActionDispatch::Http::UploadedFile class. To know the path, use #path method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.