ruby-on-railsruby-on-rails-3json

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!


Solution

  • 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|