Search code examples
ruby-on-railsspree

How to optimize adding new stock locations in Spree?


When I have a lot of products (3000 and 22000 variants), adding new stock location takes hours because Spree is creating stock items for every variant.

During this time variants table is locked and whole system is unusable. Is there some workaround for this or maybe it was fixed in some new version of Spree?

I am using spree 2.0.3.


Solution

  • I face the same problem, with >400K variants, it's impossible to add a new stock location. So, I create a script in ruby and for all variants write an insert statement to a SQL file. I must create the stock location without propagate_all_variants

    # lib/create_stock_items.rb
    
    begin
      file = File.open("stock_items.sql", "w")
    rescue IOError => e
      puts e
    end
    
    file.write("INSERT INTO spree_stock_items (stock_location_id, variant_id, backorderable) VALUES \n")
    variants = Spree::Variant.all.pluck(:id)
    length = variants.count
    
    variants.each_with_index do |variant, index|
      if index+1 == length
        file.write("(#{stock_location_id}, #{variant}, false); \n")
      else
        file.write("(#{stock_location_id}, #{variant}, false), \n")
      end
    end
    
    file.close
    

    Then run bundle exec rails runner lib/create_stock_items.rb -e production. This will create a stock_items.sql file in Rails root path, and finally load that SQL directly on BD (rails dbconsole).

    I know it's a little hack, but a very fast solution for me.