1

I am trying to follow this tutorial. It has written in previous version of Rails and I am using Rails 4. I am trying to upload file but I am getting following error:

NoMethodError in UploadController#uploadfile
undefined method `[]' for nil:NilClass

Extracted source (around line #3):

class DataFile < ActiveRecord::Base
  def self.save(upload)
    name =  upload['datafile'].original_filename
    directory = "public/data"
    # create the file path
    path = File.join(directory, name)

Rails.root: C:/Ruby193/mylibrary

Application Trace | Framework Trace | Full Trace
app/models/data_file.rb:3:in `save'
app/controllers/upload_controller.rb:6:in `uploadfile'

Here is data_file.rb

class DataFile < ActiveRecord::Base
  def self.save(upload)
    name =  upload['datafile'].original_filename
    directory = "public/data"
    # create the file path
    path = File.join(directory, name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
  end
end

Here is controller upload_controller.rb

class UploadController < ApplicationController
  def index
    render :file => 'app\views\upload\uploadfile.html'
  end
  def uploadfile
    post = DataFile.save(params[:upload])
    render :text => "File has been uploaded successfully"
  end
end

Here is uploadfile.html

<h1>File Upload</h1>
<%= form_tag({:action => 'uploadfile'}, :multipart => true) do %>
<p><label for="upload_file">Select File</label>
    <%= file_field 'upload', 'datafile' %></p>
<%= submit_tag "Upload" %>
<% end %>

What should I do? Thanks in advance

2
  • Shouldnt this form be a multipart form? Commented May 13, 2014 at 3:57
  • It's a multipart form in the tutorial, and you can't upload files without a multipart form, so yeah. I should be multipart. Commented May 13, 2014 at 4:07

1 Answer 1

1

It looks like params[:upload] isn't what you think it is. You forgot to set the form to be multipart. If fixing that doesn't make it work, start inspecting params to see what you're actually getting.

def uploadfile
  puts params.inspect # Add this line to see what's going on
  post = DataFile.save(params[:upload])
  render :text => "File has been uploaded successfully"
end

Also, it's not a great "answer," but I've had good success using paperclip to handle file uploads. If you just want something that works (rather than learning how to do it yourself), check into that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.