How to count the length (number of lines) of a csv file in Rails?
        Posted  
        
            by 
                Mathias
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Mathias
        
        
        
        Published on 2011-01-11T20:46:01Z
        Indexed on 
            2011/01/11
            20:53 UTC
        
        
        Read the original article
        Hit count: 346
        
ruby-on-rails
|csv
Hello,
I have a form (Rails) which allows me to load a .csv file using the file_field.
In the view:   
    <% form_for(:upcsv, :html => {:multipart => true}) do |f| %>
    <table>
        <tr>
            <td><%= f.label("File:") %></td>
            <td><%= f.file_field(:filename) %></td>
        </tr>
    </table>
        <%= f.submit("Submit") %>
    <% end %>
Clicking Submit redirects me to another page (create.html.erb). The file was loaded fine, and I was able to read the contents just fine in this second page. I am trying to show the number of lines in the .csv file in this second page.
My controller (semi-pseudocode):
class UpcsvController < ApplicationController
    def index
    end
    def create
        file = params[:upcsv][:filename]
        ...
        #params[:upcsv][:file_length] = file.length # Show number of lines in the file
        #params[:upcsv][:file_length] = file.size
        ...
    end
end
Both file.length and file.size returns '91' when my file only contains 7 lines.  From the Rails documentation that I read, once the Submit button is clicked, Rails creates a temp file of the uploaded file, and the params[:upcsv][:filename] contains the contents of the temp/uploaded file and not the path to the file.  And I don't know how to extract the number of lines in my original file.  What is the correct way to get the number of lines in the file?  
My create.html.erb:
<table>
    <tr>
        <td>File length:</td>
        <td><%= params[:upcsv][:file_length] %></td>
    </tr>
</table>
I'm really new at Rails (just started last week), so please bear with my stupid questions.
Thank you!
© Stack Overflow or respective owner