2016-01-20 46 views
1

大家好我有一个数据库充满了产品,我需要安排一个耙子任务每周运行。 我并不确定如何编写rake任务。一个例子是我有一个产品id = 1 name =“testname”description =“description”sku =“198”price = 12.99 我需要上传一个csv name =“testname”并更新价格为13.99显然保持身份证件完好无损。 这是我到目前为止所尝试过的,但如果有人可以帮助,那就太好了。Rake任务更新分贝中的特定产品

require 'csv' 
desc "Updates Products inside an ActiveRecord table" 
task :update_prods, [:filename] => :environment do 
    products = Spree::Product.all 
    CSV.foreach('update_prods.csv', :headers => true) do |row| 
    Spree::Product.update!(row.to_hash) 
end 
end 

回答

0

这里是我们如何进口产品从Shopify到狂欢可能给你如何去了解这个https://gist.github.com/dgross881/b4f1ac96bafa2e29be7f一些思想依据。

def update_products 

    puts 'Updating Products...' 
    require 'csv' 
    products_csv = File.read(Rails.root.join('lib/assets/products_list.csv')) 
    products = CSV.parse(products_csv, headers: true) 

    products.each_with_index do |row, index| 
    Rails.logger.info { [#{index + 1}..#{products.length}] Updating product: #{row['title']} } 
    product = Spree::Product.find!(row['id']) 
    update_product = product.update_attributes(name: row['title'], description:row['description'], 
    meta_title: row['seo_title'], meta_description: row['seo_description'], 
    meta_keywords: "#{row['handle']}, #{row['title']}, the Squirrelz", 
    available_on: Time.zone.now, price: row['price'], 
    shipping_category: Spree::ShippingCategory.find_by!(name: 'Shipping')) 

    update_product.tag_list = row['tags'] 
    update_product.slug = row['handle'] 
    update_product.save! 
    end 
    Rails.logger.info { "Finished Updating Products" } 
end 

def update_variants 
    puts 'updating Variants...' 
    require 'csv' 
    products_variants_csv =File.read(Rails.root.join('lib/assets/variants_list.csv')) 

    products_variants = CSV.parse(products_variants_csv, headers: true) 

    products_variants.each_with_index do |row, index| 
    puts "[#{index + 1}..#{products_variants.length}] Adding Variant (#{row['sku']} to Product: #{Spree::Product.find_by!(slug: row['handle']).name})" 
    variant = Spree::Variant.find_by!(sku: row['sku'] 
    update_variant = variant.update_attributes!(sku: row['sku'], stock_items_count: row['qty'], cost_price: row['price'], weight: row['weight'] 

    unless row['option1'].blank? 
     variant.option_values << Spree::OptionValue.find_by!(name: row['option1']) 
    end 
    unless row['option2'].blank? 
     variant.option_values << Spree::OptionValue.find_by!(name: row['option2']) 
    end 
    variant.save! 
    end 
    puts 'Updated Variants' 
end