J
John Mcleod
Hello all,
I've added a couple new columns to a database table. I was trying to
add default data as the .csv file is being read into the table. I'm not
sure on how to do this.
- import_irb_file -
def import_irb_file
# set file name
file = params[:irb][:file]
deletecount = 0
rowcount = 0
# delete all irb records
@irb = Irb.find
all, :conditions => "reconciled = 1")
@irb.each { |i|
i.destroy
deletecount+=1
}
Irb.transaction do
FasterCSV.parse(file,
:headers => true,
:header_converters => lambda { |h| h.tr(" ",
"_").delete("^a-zA-Z0-9_")},
:converters => :all ) do |row|
Irb.create!(row.to_hash)
rowcount += 1
end
end
# if successful then display, then redirect to index page
flash[:notice] = "Successfully deleted #{deletecount} and added
#{rowcount} IRB record(s)."
redirect_to :action => :index
rescue => exception
file_name = params[:irb]['file'].original_filename
file_parts = params[:irb]['file'].original_filename.split('.')
ext = file_parts[1]
if ext != 'csv'
error = "CSV file is required"
else
error = ERB::Util.h(exception.to_s) # get the error and HTML
escape it
end
# If an exception in thrown, the transaction rolls back and we end
up in this
# rescue block
flash[:error] = "Error adding projects to IRB table. (#{error}).
Please try again."
redirect_to :controller => 'irbs', :action => 'new'
end
Thank you for any and all help with this.
JohnM
I've added a couple new columns to a database table. I was trying to
add default data as the .csv file is being read into the table. I'm not
sure on how to do this.
- import_irb_file -
def import_irb_file
# set file name
file = params[:irb][:file]
deletecount = 0
rowcount = 0
# delete all irb records
@irb = Irb.find
@irb.each { |i|
i.destroy
deletecount+=1
}
Irb.transaction do
FasterCSV.parse(file,
:headers => true,
:header_converters => lambda { |h| h.tr(" ",
"_").delete("^a-zA-Z0-9_")},
:converters => :all ) do |row|
Irb.create!(row.to_hash)
rowcount += 1
end
end
# if successful then display, then redirect to index page
flash[:notice] = "Successfully deleted #{deletecount} and added
#{rowcount} IRB record(s)."
redirect_to :action => :index
rescue => exception
file_name = params[:irb]['file'].original_filename
file_parts = params[:irb]['file'].original_filename.split('.')
ext = file_parts[1]
if ext != 'csv'
error = "CSV file is required"
else
error = ERB::Util.h(exception.to_s) # get the error and HTML
escape it
end
# If an exception in thrown, the transaction rolls back and we end
up in this
# rescue block
flash[:error] = "Error adding projects to IRB table. (#{error}).
Please try again."
redirect_to :controller => 'irbs', :action => 'new'
end
Thank you for any and all help with this.
JohnM