【问题标题】:Having issues importing a CSV File using FasterCSV使用 FasterCSV 导入 CSV 文件时遇到问题
【发布时间】:2011-06-28 02:19:16
【问题描述】:


我是 Rails 新手,我已经知道如何从我的数据库中导出结果,但是我在从 CSV 文件创建新记录时遇到了问题。使用下面列出的代码,我希望能够导入 CSV 文件并使用来自用户的会话数据填写最后两列。现在我只是插入了一个静态数字来尝试让它工作。我目前收到“无法将 ActionDispatch::Http::UploadedFile 转换为字符串”作为错误消息

CSV 文件

名称、任务、expected_results、require_id 测试名称 1,打开文件,打开,t 测试名称 2,读取文件,读取,t 测试名称 3,关闭文件,关闭,f

控制器

  def csv_import  
    file = params[:file]  
    FasterCSV.foreach(file,{:headers => true, :row_sep => :auto}) do |row|  
        Script.create!(:name => row[0],  
                      :task => row[1],  
                      :expected_results => row[2],  
                      :require_id => row[3],    
                      :department_id => 1,  
                      :category_id => 1)  
    end  
  end

查看

<%=form_tag '/script_admin/csv_import', :multipart => true do%>
<%= file_field_tag "file" %><br/>
<%= submit_tag("Import") %>
<% end %>

数据库迁移

class CreateScripts < ActiveRecord::Migration
  def self.up
    create_table :scripts do |t|
      t.integer     :department_id,       :null => false
      t.integer     :category_id,         :null => false
      t.string      :name,                :null => false
      t.string      :task,                :null => false
      t.string      :expected_results,    :null => false
      t.boolean     :require_id,          :null => false,   :default => "t"
      t.timestamps
    end
  end

  def self.down

drop_table :scripts

结束 结束

如有任何帮助,我们将不胜感激

~凯尔

【问题讨论】:

    标签: ruby-on-rails-3 file-upload fastercsv


    【解决方案1】:

    感谢 James Gray,问题得以解决

      def csv_import
        file = params[:file]
        FCSV.new(file.tempfile, :headers => true).each do |row|
            Script.create!(:name => row[0],
                          :task => row[1],
                          :expected_results => row[2],
                          :require_id => row[3],
                          :department_id => 1,
                          :category_id => 1)
        end
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-10
      • 2016-04-06
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      相关资源
      最近更新 更多