Rake任务更新db中的特定产品

时间:2016-01-20 11:21:27

标签: ruby-on-rails rake task spree

大家好我拥有一个装满产品的数据库,我需要安排一个rake任务每周运行一次。 我不确定如何编写rake任务。一个例子是我有一个产品id = 1 name =“testname”description =“description”sku =“198”price = 12.99 我需要上传名称为“testname”的csv并将价格更新为13.99,同时显然保持id不变。 这是我到目前为止所尝试过的,但如果有人能提供帮助那就不完整。

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

1 个答案:

答案 0 :(得分:0)

以下是我们如何将产品从Shopify导入Spree的一个要点,它可以为您提供有关如何解决此问题的一些想法{。{3}}。

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