Ruby on rails,读取和显示csv文件不工作? [英] Ruby on rails, reading and showing csv-file doesn't work?

查看:148
本文介绍了Ruby on rails,读取和显示csv文件不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby on Rails中实现,我只想要一些容易做的事情,我只想读取一个csv文件,然后在视图中显示输出。我有一些代码看起来很好,但我总是得到错误:无法将Tempfile转换为字符串
这是我的控制器:

I am implementing in Ruby on Rails and I just want something easy to do, i just want to read a csv file and then show the output in a view. I have some code which seems good to me, but i always get the errror : can't convert Tempfile into String This is my controller:

def match
file = params[:file]

@original_filename = file.original_filename
tmpfile = Tempfile.new("redmine_project_importer")
if tmpfile
    tmpfile.write(file.read)
    tmpfile.close
    tmpfilename = File.basename(tmpfile.path)
      if !$tmpfiles
        $tmpfiles = Hash.new
      end
      $tmpfiles[tmpfilename] = tmpfile
    else
      flash[:error] = "Cannot save import file."
      return
    end
 session[:importer_tmpfile] = tmpfilename
sample_count = 5
i = 0
@samples = []
FasterCSV.open(file, "r") do |row|       
        @samples[i] = row
        i += 1
        if i > sample_count
            break
        end
    end

<% form_tag({:action => 'result'}, {:multipart => true}) do %>
<table>  

<% @samples.each do |sample| %>
  <tr>
     <td>sample</td>    
  </tr>
<% end %>
</table>

有人可以帮助我吗?
Greetz

Someone who can help me out? Greetz

推荐答案

1) FasterCSV.open()需要一个String文件名,并且你传递一个File对象给它。

1) FasterCSV.open() requires a String filename, and you're passing a File object to it.

2) FasterCSV.foreach(filename)如果你想迭代行。或 FasterCSV.open()。每个

2) It's FasterCSV.foreach(filename) if you want to iterate lines. Or FasterCSV.open().each

但在你的情况下,如果你有一个上传的File参数, 更好地与

But in your case, if you have an uploaded File parameter, you're better off with

FasterCSV.new(params[:file]).each do |line|

等等

这篇关于Ruby on rails,读取和显示csv文件不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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