calazans10
calazans10

Reputation: 13

How to upload a text file without saving and parse the content into a database with RoR

I need to upload a text file without saving it in the database. My goal is to upload this file and automatically have to take your content and save it in my database.

my file: data.txt

name age occupation
julio 19 student
ramon 20 student

my database:

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

Does anyone have any idea how this can be done? I searched on the internet, but found no solution to my case. I need help.

Upvotes: 1

Views: 1936

Answers (1)

Yuri  Barbashov
Yuri Barbashov

Reputation: 5437

= form_tag url, {multipart: true} do
  = file_field_tag :file
  ....

in controller

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

Upvotes: 2

Related Questions