Ruben
Ruben

Reputation: 1093

Ruby on rails, reading and showing csv-file doesn't work?

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

Upvotes: 0

Views: 551

Answers (2)

Leonid Shevtsov
Leonid Shevtsov

Reputation: 14189

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

Upvotes: 1

Wahaj Ali
Wahaj Ali

Reputation: 4113

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

Upvotes: 0

Related Questions