| Message: 74037 |
 |
BY: Demetrius Olsen (demetriuso) DATE: 2009-05-13 04:46 SUBJECT: RE: Help setting up FasterCSV to import a file Sorry for not being very clear. I'm a newbie :-)
I want to allow teachers to import students via a CSV file. In my controller, I have:
require 'fastercsv'
class ImportStudentController < ApplicationController
def index
end
def csv_import
file = params[:csv_import][:file]
logcount=0
Student.transaction do
FasterCSV.parse(file, :headers => true) do |row|
current_user.students.create!(row.to_hash)
logcount += 1
end
end
flash[:notice] = "Successfully added #{logcount} Student(s)."
redirect_to :action => :index
rescue => exception
# If an exception is thrown, the transaction rolls back and we end up in this rescue block
error = ERB::Util.h(exception.to_s) # get the error and HTML escape it
flash[:error] = "Error adding logs. (#{error}). Please try again."
redirect_to :action => :index
end
end
In my view, I have:
<% if flash[:notice] -%>
<%= flash[:notice] %>
<% end -%>
<% if flash[:error] -%>
<%= flash[:error] %>
<% end -%>
<% form_for :csv_import, :url=>{ :controller=>"import_student", :action => 'csv_import'},
:html => { :multipart => true } do |f| %>
<p><%= f.label :file, 'Import Students file' %><br/>
<%= f.file_field :file -%></p>
<p><%= submit_tag "Submit" %></p>
<% end %>
These files work in another app that I found online, but not in mine. My original question should have been, what am I missing? Why would this code work in one app but not in mine? Thanks again. | |