Note that there are some explanatory texts on larger screens.

plurals
  1. POCount the length (number of lines) of a CSV file?
    primarykey
    data
    text
    <p>I have a form (Rails) which allows me to load a .csv file using the <code>file_field</code>. In the view: </p> <pre><code> &lt;% form_for(:upcsv, :html =&gt; {:multipart =&gt; true}) do |f| %&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;%= f.label("File:") %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= f.file_field(:filename) %&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;%= f.submit("Submit") %&gt; &lt;% end %&gt; </code></pre> <p>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. </p> <p>My controller (semi-pseudocode):</p> <pre><code>class UpcsvController &lt; 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 </code></pre> <p>Both <code>file.length</code> and <code>file.size</code> 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 <code>params[:upcsv][:filename]</code> contains the contents of the temp/uploaded file and not the <em>path</em> 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? </p> <p>My create.html.erb:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;File length:&lt;/td&gt; &lt;td&gt;&lt;%= params[:upcsv][:file_length] %&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I'm really new at Rails (just started last week), so please bear with my stupid questions. </p> <p>Thank you!</p> <p><strong>Update:</strong> apparently that number '91' is the number of individual characters (including carriage return) in my file. Each line in my file has 12 digits + 1 newline = 13. 91/13 = 7.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload