Created
October 17, 2009 18:53
-
-
Save wemerson/212429 to your computer and use it in GitHub Desktop.
Spree Variant Uploads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Admin::VariantsController < Admin::BaseController | |
... | |
#add this to controllers/admin/variants_controller.rb or override in extension | |
#update directory must exist | |
UPDATE_DIRECTORY = 'public/updates' | |
require 'fastercsv' | |
def variants_csv_import | |
file = params[:dump][:file] | |
csv_import(file, "variants") | |
end | |
def csv_import(file, table_name) | |
#working on making this generic, so will work with any model but having problems with table objects. | |
#for now, must specify model in code below, substitute model name for Variant | |
#mymodel = table_name.classify.constantize | |
t = Time.now | |
filepath = File.join(UPDATE_DIRECTORY, t.strftime("%Y%m%d%H%M%S") + ".txt") | |
if file.is_a? StringIO | |
File.open(filepath, File::RDWR|File::CREAT) { |f| f << file.read } | |
else | |
FileUtils.cp(file.path, filepath) | |
end | |
#set for tab-delimited, for csv use :col_sep => "\c" | |
#first line of import file must contain correct field names separated by delimiters | |
#does not need all fields and order doesn't matter except for key. | |
n = 0 | |
u = 0 | |
FCSV.foreach(filepath, | |
:col_sep => "\t", | |
:headers => true, | |
:header_converters => :symbol ) do |line| | |
row = line.to_hash | |
#key must be specified | |
#sku must be key in this system--it's second field | |
key = line[1] | |
@item = Variant.find_by_sku(key) | |
if @item | |
row.merge({"id" => @item.id}) | |
@item.update_attributes(row) | |
u = u + 1 | |
else | |
@item = Variant.new | |
row.merge({"id" => @item.id}) | |
@item = Variant.create(row) | |
n = n + 1 | |
end | |
end | |
#add error handling | |
flash[:notice]="CSV Import Successful. #{n}records created, #{u} records updated." | |
redirect_to :controller => 'admin/products', :action => 'index' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment