Undefined `path 'method for nil: NilClass when trying to import CSV

I am following Import CSV Railscast , and it is straightforward.

I added require 'csv'to myconfig/application.rb

In my BuildingsControllerI created a new action import, for example:

def import
  Building.import(params[:file])
  redirect_to root_url, notice: "Buildings imported."
end

In my opinion, I have the following:

<h2>Import Buildings</h2>
<%= form_tag import_buildings_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

This is in my model Building.rb:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    building = find_by_name(row["name"]) || new
    building.attributes = row.to_hash.slice(*accessible_attributes)
    building.save!
  end
end

In mine routes.rb, I have this:

  resources :buildings do
    collection { post :import }
  end

When I click the import button on my view, I get this error:

NoMethodError at /buildings/import

Message undefined method `path' for nil:NilClass
File    /myapp/app/models/building.rb
Line    23

Thoughts?

+3
source share
1 answer

From a comment: you are most likely submitting a form without selecting a file :)

+2
source

All Articles