我是 Rails 的新手,在我为本地高中开发的移动 Web 应用程序方面一直在稳步取得进展,但遇到了一个让我感到难过的问题。我希望这里的集体知识能为我指明正确的方向。
我有一个学校运动员模型(名字、姓氏、高度、体重、毕业年份,- 标准的东西)正在运行(通过标准脚手架生成的 CRUD)现在我想添加导入记录的能力通过 CSV 上传。
为了不重新发明轮子,我正在关注 this example from Rich on Rails .为了熟悉它,我创建了一个单独的 Rail 项目并按照示例进行操作,一切都按预期进行。伟大的。现在要集成到我现有的项目中。
除了一个异常(exception),一切似乎都很好地集成了——CSV 文件从未在参数中传递到我的模型,我不明白为什么。我确信这是显而易见的事情,但我已经盯着这个问题看了好几个小时,但看不出我做错了什么。
这是我的 Athletes Controller 的一部分:
class AthletesController < ApplicationController
before_action :set_athlete, only: [:show, :edit, :update, :destroy]
# GET /athletes
# GET /athletes.json
def index
@athletes = Athlete.all.order(:lastname, :firstname)
end
# POST /athletes/import
# POST /athletes/import.json
def import
logger.info(params.to_yaml)
begin
Athlete.import(params[:file])
redirect_to page_path('admin'), notice: "Athletes imported."
rescue
redirect_to page_path('admin'), notice: "Invalid CSV file format."
end
end
# GET /athletes/1
# GET /athletes/1.json
def show
end
# GET /athletes/new
def new
@athlete = Athlete.new
end
# GET /athletes/1/edit
def edit
end
我的模型是这样的:
class Athlete < ActiveRecord::Base
# an athlete can be on more than one team
has_and_belongs_to_many :teams, through: :athletes
require 'csv'
## CSV import
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
athlete_hash = row.to_hash # exclude the ? field
athlete = Athlete.where(id: athlete_hash["id"])
if athlete.count == 1
athlete.first.update_attributes
else
Athlete.create!(athlete_hash)
end # end if !athlete.nil?
end # end CSV.foreach
end # end self.import(file)
我已经将它添加到我的索引 View 中进行测试,稍后它将在管理区域中:
<div>
<h3>Import a CSV File</h3>
<%= form_tag import_athletes_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import CSV" %>
<% end %>
</div>
无论我做什么,我都无法将 file_field_tag 的值传递给 Controller 。如果我使用 text_field_tag 添加其他字段,它们会按预期通过,但 file_field_tag 值永远不会。
--- !ruby/hash:ActionController::Parameters
utf8: "✓"
authenticity_token: it3yBxBnzA4UQ/NILP5GNoYJeO5dyg+Z+VfhE/C6p7k=
commit: Import CSV
action: import
controller: athletes
Redirected to http://localhost:3000/
Completed 302 Found in 8ms (ActiveRecord: 0.0ms)
我很困惑 - 如果有人对我可能做错了什么有任何想法,我将不胜感激。我有大约 300 名运动员要导入,但不想输入。
最佳答案
事实证明,因为我在我的框架中使用 jQuery Mobile,所以我需要将“data-ajax=false”添加到我的表单标记中。对我的表单的这种更改允许文件参数在 Controller 中可见:
<h3>Import a CSV File</h3>
<%= form_tag(import_athletes_path, { :multipart => true, :'data-ajax' => false }) do %>
<%= file_field_tag :file %>
<%= submit_tag "Import CSV" %>
<% end %>
</div>
不久前,我想起读过一些关于文件上传和默认情况下 jQuery Mobile 不工作的内容。这是由于 jQM 使用的标准 AJAX 导航。
关于ruby-on-rails - 上传文件参数未通过 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25626402/