I’m new to ROR and still trying to wrap my mind around the MVC construct. Hope someone can spot what is probably a simple error here.
I need to have a user upload a CSV file, parse the header (the table field names) then each row of data, and import the data into its respective tables.
In the view I have:
<% form_tag ({:action => ‘uploadFile’}, :multipart => true) do %>
Select File : <%= file_field 'upload', 'datafile' %>
<%= submit_tag "Upload" %> <% end %>in the controller:
class UploadController < ApplicationController
def index render :file => ‘app\views\upload\uploadfile.html.erb’ end
def uploadFile
post = Import.proc_csv( params[:upload])
flash[:notice] = "File imported successfully"
redirect_to :action => :index
rescue
flash[:error] = "Error importing file"
redirect_to :action => 'index'
end
end
and in the model:
class Import < ActiveRecord::Base
require ‘fastercsv’
def self.proc_csv(upload) row_count = 0 FasterCSV.foreach([:csv_import][:file], :headers => :first_row) do |row|
@gr = Genotype_runs.create(:genotype_date_1=>row[4],:genotype_date_2=>row[5],:genotype_date_3=>row[6])
# use the id of the Genotype_runs record to link to Genotype_data rec.
Genotype_data.create(:genotype_run_id=> gr.id, :box=>row[0], :subjectid=>row[1], :labid=>row[2], :well=>row[4], :created_at=>Time.now,:updated_at=>Time.now)
# print message showing import
$stderr.print "\r%5d ..." % csv.lineno
$stderr.flush
row_count = row_count + 1
end
end
def self.save(upload) name = upload[‘datafile’].original_filename directory = “public/data/import” # create the file path path = File.join(directory, name) # write the file File.open(path, “wb”) { |f| f.write(upload[‘datafile’].read) } end end
The file upload screen allows me to upload a file, but when I submit it, I get the following error: