1

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

我的文件: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

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

4

1 回答 1

2
= 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
于 2012-05-20T12:10:14.057 回答