Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in file contents rails

I have a form that is attempting to read in a JSON file for parsing/actions/etc. I'm having problems getting it to read in the controller.

View:

<%= form_tag({:controller => :admins, :action => :upload_json}, {:multipart => true, :method => :post}) do |f| %>

    <%= file_field_tag 'datafile' %>

<%= submit_tag "Upload" %>

Controller:

def upload_json

  file_data = params[:datafile]

  File.read(file_data) do |file|

     file.each do |line|
       ## does stuff here....
     end
  end

end

A similar function works in my seed.rb file when I'm seeding data - just can't get it to read in an uploaded file.

The error I'm getting is: can't convert ActionDispatch::Http::UploadedFile into String.

Thanks in advance for the help!

like image 256
matthewvb Avatar asked Sep 25 '12 19:09

matthewvb


People also ask

How can you read an entire file and get each line in Ruby?

Use File#readlines to Read Lines of a File in Ruby File#readlines takes a filename to read and returns an array of lines. Newline character \n may be included in each line. We must be cautious when working with a large file, File#readlines will read all lines at once and load them into memory.

How do you read a line by line in Ruby?

Overview. The IO instance is the basis for all input and output operations in Ruby. Using this instance, we can read a file and get its contents line by line using the foreach() method. This method takes the name of the file, and then a block which gives us access to each line of the contents of the file.


1 Answers

Figured it out. Needed to change:

file_data = params[:datafile]

to

file_data = params[:datafile].tempfile

And decided to use the .open function to change:

File.read(file_data) do |file|

to

File.open(file_data, 'r') do |file|  
like image 169
matthewvb Avatar answered Oct 08 '22 16:10

matthewvb