未定义方法`path'为nil:NilClass在尝试CSV导入时 [英] undefined method `path' for nil:NilClass when trying CSV import

查看:286
本文介绍了未定义方法`path'为nil:NilClass在尝试CSV导入时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循导入CSV轨道

我添加了 require'csv'到我的 config / application .rb

我在 BuildingsController 中创建了一个新的 import 动作如下:

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

在我看来,我有:

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

这是在我的 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

在我的 routes.rb ,我有这个:

  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

推荐答案

从注释:您很可能在不选择文件的情况下提交表单:)

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

这篇关于未定义方法`path'为nil:NilClass在尝试CSV导入时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆