ruby on rails import csv from upload file to Activ

2019-09-05 05:09发布

I hit a roadblock here and need help. I want to be able to import csv file to my Active Record. Either with SmarterCSV or some other way

Here is my database

create_table "ques", force: true do |t|
    t.integer  "rikt_nr"
    t.integer  "start_nr"
    t.integer  "end_nr"
    t.datetime "created_at"
    t.datetime "updated_at"
end

here is my view

<h2>Import Ques</h2>  

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

here is my route

resources :ques do  
  collection { post :import }  
end  
  root to: 'ques#index' 

and my controller

def import  
  Que.import(params[:file])  
   redirect_to root_url, notice: "Ques imported."  
end 

and the model

def self.import(file)  
  CSV.foreach(file.path, headers: true) do |row|  
   Que.create! row.to_hash  
  end  
end  

and the csv file is looking like this

Id;Rikt nr;Start nr;End nr;Created at;Updated at
1;8;4486550;4486650;October 28, 2014 08:42;October 28, 2014 08:42
2;8;4486700;4486755;October 28, 2014 08:42;October 28, 2014 08:42

I have looked at all sort of guides, but I just cant get it to work.

2条回答
相关推荐>>
2楼-- · 2019-09-05 05:34

First: you don't use smarter_csv in your example, but standard Ruby CSV.
Second: smarter_csv gives you options to specify the delimiting character but doesn't auto detect it.

in conclusion, you import should look like

def self.import(file)  
  SmarterCSV.process(file.path, col_sep: ';') do |row|  
   Que.create! row 
  end  
end  
查看更多
劫难
3楼-- · 2019-09-05 05:37

For anybody else that is having a problem with this. This is how I solved it. First off change the csv file to have "," as the delimiters

Then use the code I have, but change the controller to this

def import
      csv_file = params[:file].read
      CSV.parse(csv_file) do |row|
      ques = Que.create(rikt_nr: row[0], start_nr: row[1], end_nr: row[2])
      ques.save
    end
 redirect_to ques_path, notice: "Que added"

end

and it works

查看更多
登录 后发表回答