本文介绍了ruby on rails使用Smarter csv将csv从上传文件导入到活动记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里打了一个路障,需要帮助。我想能够导入csv文件到我的活动记录。使用SmarterCSV或其他方式



这是我的数据库

  create_tableques,force:true do | t | 
t.integerrikt_nr
t.integerstart_nr
t.integerend_nr
t.datetimecreated_at
t.datetimeupdated_at
end

这里是我的观点

 < h2>导入Ques< / h2> 

<%= form_tag import_ques_path,multipart:true do%>
<%= file_field_tag:file%>
<%= submit_tag导入%>
<%end%>

这里是我的路线

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

和我的控制器

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

和模型

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

并且csv文件看起来像这样

  Id; Rikt nr; Start nr; End nr; Created at;更新于
1; 8; 4486550; 4486650; 2014年10月28日08:42; 2014年10月28日08:42
2; 8; 4486700; 4486755; 2014年10月28日08:42; 2014年10月28日08:42

我看了所有的指南,但我只是无法得到它的工作。

解决方案

对于有此问题的任何人。这是我如何解决它。首先,更改csv文件以使用,作为分隔符



然后使用我拥有的代码,但将控制器更改为

  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,通知:Que加入

end

>

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.

解决方案

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

这篇关于ruby on rails使用Smarter csv将csv从上传文件导入到活动记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:17
查看更多