【问题标题】:Ruby on Rails 4 - CSV import - no implicit conversion into stringRuby on Rails 4 - CSV 导入 - 没有隐式转换为字符串
【发布时间】:2015-05-22 11:39:14
【问题描述】:

我正在尝试将 CSV 数据导入到我的 mysql 数据库,但是当我尝试上传文件时遇到了错误:

no implicit conversion of ActionDispatch::Http::UploadedFile into String

这是 CSV 文件中的一行:

751,"01/17/2015","11:17:32","60","TDFSRDSK","2","10","-1","0","3","","26","3","","","1","0"

这是导入的代码,在 product.rb 中

def self.import(file)
  CSV.foreach(file) do |row|
    id, jour, heure, valeur, app, a, b, c, d, e, f, g, h, i, j, k, l = row
    userid = current_user.id
    product = Product.create(date: jour, valeur: valeur,user_id: userid)
  end
end

在 product_controller.rb 中

def import
 Product.import(params[:file])
 redirect_to_root_url, notice "Products imported"
end

在索引中:

<%= form_tag import_products_path, multipart: true do %>
 <%= file_field_tag :file %>
 <%= submit_tag "Import" %>
<% end %>

在 routes.rb 我有:

resources :products do
 collection {post :import}
end

【问题讨论】:

    标签: mysql ruby-on-rails ruby csv


    【解决方案1】:

    尝试在参数中给出params[:file].path。像这样,

    Product.import(params[:file].path)
    

    结帐this

    【讨论】:

    • 谢谢我设法摆脱了您的解决方案的错误消息,现在它似乎可以工作但没有数据添加到 SQL 表中
    • 在创建时,尝试使用 Product.create!(..) 。因此,如果有的话,它会抛出异常。
    • 谢谢,我猜我到 sql 的数据映射有问题,因为它们都显示为 NULL 并且没有创建,因为我在模型中的字段上有一个“验证”。我会尝试找到映射 ip 的正确方法
    【解决方案2】:

    你需要这样做:

    CSV.foreach(file.path)
    

    您的file 持有ActionDispatch::Http::UploadedFile 类的实例。要知道路径,请使用#path 方法。

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2014-06-21
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多