Mukaddes
Mukaddes

Reputation: 307

Ruby Rails: Upload File

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

Upvotes: 1

Views: 1485

Answers (1)

James Mason
James Mason

Reputation: 4306

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.

Upvotes: 1

Related Questions