【问题标题】:undefined method `path' for nil:NilClass when trying CSV import尝试 CSV 导入时 nil:NilClass 的未定义方法“路径”
【发布时间】:2013-01-16 14:19:58
【问题描述】:

我正在关注Import CSV Railscast,它是直截了当的。

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

在我的BuildingsController 中,我创建了一个新的import 操作,如下所示:

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

当我单击视图上的“导入”按钮时,出现此错误:

NoMethodError at /buildings/import

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

想法?

【问题讨论】:

  • 这意味着 params[:file]nil 但我不明白为什么会这样,除非您在不选择文件的情况下提交表单
  • 哦哇...我很尴尬。我正在导入一个空表单:(表单的方式和我的应用程序中的样式,它只有一个用于导入的按钮。我选择那个以为我正在按下“选择文件”。我的错。如果你将它添加为一个答案,我会接受。隐藏脸

标签: ruby-on-rails ruby-on-rails-3 csv import


【解决方案1】:

来自评论:您很可能在没有选择文件的情况下提交表单:)

【讨论】:

    猜你喜欢
    • 2016-07-03
    • 2020-05-05
    • 1970-01-01
    • 2012-05-19
    • 2014-04-21
    • 2016-06-15
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多