【问题标题】:How to upload a text file without saving and parse the content into a database with RoR如何在不保存的情况下上传文本文件并将内容解析到具有 RoR 的数据库中
【发布时间】:2012-05-27 05:10:07
【问题描述】:

我需要上传一个文本文件而不将其保存在数据库中。我的目标是上传此文件并自动获取您的内容并将其保存在我的数据库中。

我的文件:data.txt

name age occupation
julio 19 student
ramon 20 student

我的数据库:

class CreateStudents < ActiveRecord::Migration
   def change
     create_table: students do |t|
       t.string "name"
       t.integer "age"
       t.string "occupation"

       t.timestamps
     end
   end
end

有谁知道如何做到这一点?我在互联网上搜索,但没有找到解决我的情况的方法。我需要帮助。

【问题讨论】:

  • 似乎任何上传库和 CSV 处理的组合都可以解决问题。

标签: ruby-on-rails ruby file parsing upload


【解决方案1】:
= form_tag url, {multipart: true} do
  = file_field_tag :file
  ....

在控制器中

if params[:file]
  lines = params[:file].tempfile.readlines.map(&:chomp) #readlines from file & removes newline symbol
  lines.shift #remove first line 
  lines.each do |l| 
    m = l.match(/(\S+)\s(\d+)\s(\S+)/) #parse line 
    Student.create {name: m[1],age: m[2], occupation: m[3]}
  end
end

【讨论】:

  • 但最好异步执行 (delayed_job,redis...)
  • 如何将此表格翻译为 erb 格式?我不使用haml。
  • 只需添加 true} do %>
  • 我试了一下,但它返回此消息:“未定义的局部变量或方法 `url'”
  • ofc) 请阅读 guides.rubyonrails.org/form_helpers.html#uploading-files 并创建您的路线、控制器、动作...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多