Rails - 无法从CSV文件导入数据 [英] Rails - Can't import data from CSV file

查看:110
本文介绍了Rails - 无法从CSV文件导入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从CSV档案汇入资料,我不想储存档案。我在这里找到了一个类似的问题: Ruby on Rails - 导入数据来自CSV文件

I am trying to import data from a CSV file, I don't want to save the file. I have found a similar question here: Ruby on Rails - Import Data from a CSV file

但是,当我尝试使用此解决方案时会收到错误。

However, when I try and use this solution I get an error.

我的表单如下:

Import a CSV file
<%= file_field_tag :file %>

<div class="actions form-group" id="button_text">
<p>
<%= button_tag(type: 'submit', class: "btn btn-primary button-submit") do %>
Submit
<% end %>

在新页面上提交此表单时调用create操作,然后调用create操作:

On the new page the submission of this form calls the create action, the create action then calls the line:

Product.import(params[:file])

我的模型中有以下import方法:

I have the following import method in my model:

def self.import(myfile)
    require 'csv'    

    csv_text = File.read(myfile)
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|

    end
end

其中'myfile'是params [ :file]。

where 'myfile' is params[:file].

我知道我没有对数据做任何事情。我得到一个错误与 csv_text = File.read(myfile)这是:没有这样的文件或目录@ rb_sysopen - X.csv

I am aware I am not doing anything with the data yet. I am getting an error with line csv_text = File.read(myfile) which is: No such file or directory @ rb_sysopen - X.csv

当我寻找一个解决方案,我看到.path被使用。如果我把这行改为 csv_text = File.read(myfile.path)我得到错误:undefined方法`path'为X.csv:String

When looking for a solution I have seen .path is used. If i change this line to csv_text = File.read(myfile.path) I get the error: undefined method `path' for "X.csv":String

有人可以帮忙吗?我觉得我必须非常接近一个解决方案,但我只是继续往返这两个错误之间。

Can anybody help? I feel like I must be very close to a solution but I just keep going round and round between these two errors. Is it possible to get the data from the csv without saving it first?

感谢您的时间

推荐答案

你可以这样做。
.html.erb

you can do something like this way .html.erb

<%= form_for(<object>, url: <path>, method: :post, remote: :true, html: {
  multipart: true, }) do |f| %>
    <input type="file" name="file_batch_upload"  accept=".csv />
<% end %>

//定义该函数

def self.import(file)
    require 'csv'    

    csv_text = File.read(file.tempfile)
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
     //row["name"]
    end
end

这篇关于Rails - 无法从CSV文件导入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆