gpt4 book ai didi

ruby-on-rails - 未定义方法 `path' 为 nil :NilClass when trying CSV import

转载 作者:行者123 更新时间:2023-12-02 02:06:42 24 4
gpt4 key购买 nike

我正在关注 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

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

NoMethodError at /buildings/import

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

想法?

最佳答案

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

关于ruby-on-rails - 未定义方法 `path' 为 nil :NilClass when trying CSV import,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14643449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com