简体   繁体   English

ruby on rails使用更智能的csv将csv从上传文件导入到Active Records

[英]ruby on rails import csv from upload file to Active Records using Smarter csv

I hit a roadblock here and need help. 我在这里遇到障碍,需要帮助。 I want to be able to import csv file to my Active Record. 我希望能够将csv文件导入到我的活动记录中。 Either with SmarterCSV or some other way 使用SmarterCSV或其他方式

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 和CSV文件看起来像这样

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. 我看过各种指南,但是我无法使其正常工作。

First: you don't use smarter_csv in your example, but standard Ruby CSV. 首先:在示例中,您没有使用smarter_csv ,而是使用了标准的Ruby CSV。
Second: smarter_csv gives you options to specify the delimiting character but doesn't auto detect it. 第二: smarter_csv提供选项来指定定界字符,但不会auto detect它。

in conclusion, you import should look like 总之,您import应类似于

def self.import(file)  
  SmarterCSV.process(file.path, col_sep: ';') do |row|  
   Que.create! row 
  end  
end  

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 首先,将csv文件更改为以“,”作为分隔符

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 它有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM