undefined method `path' for nil:NilClass when

2019-02-19 04:47发布

问题:

I am following the Import CSV Railscast and it is straight forward.

I added require 'csv' to my config/application.rb

In my BuildingsController I created a new import action like so:

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

In my view, I have this:

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

This is in my Building.rb model:

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 my 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?

回答1:

From the comment: You are most probably submitting the form without choosing a file :)