0

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

and my view is just:

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

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

Someone who can help me out? Greetz

2 Answers 2

1

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

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

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

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

et cetera

Sign up to request clarification or add additional context in comments.

1 Comment

I've done this, I do not have an error anymore. But i still don't have any output. Just like @samples is empty, how come this?
0

I haven't worked with FasterCSV, but I think you should give Spreadsheet a look - http://spreadsheet.ch/

You should be able to read a csv file as simply as this:

book = Spreadsheet.open path_to_file
sheet  = book.worksheet 0

You could then iterate through the rows and perform whatever action you want:

sheet.each do |row|
  #code
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.