From cd53ec1a4f84948e7d449e26bf19da2e0c7ef737 Mon Sep 17 00:00:00 2001 From: Pau Perez Date: Thu, 6 Sep 2018 13:16:20 +0200 Subject: [PATCH] Replace exception with DB uniqueness constraint By forbidding more than a row per variant in the spree_stock_items we can ensure all variants have a single stock_item associated. --- ...641_add_uniqueness_of_variant_id_to_spree_stock_items.rb | 5 +++++ db/schema.rb | 3 ++- lib/open_food_network/variant_stock.rb | 6 ------ 3 files changed, 7 insertions(+), 7 deletions(-) create mode 100644 db/migrate/20180906094641_add_uniqueness_of_variant_id_to_spree_stock_items.rb diff --git a/db/migrate/20180906094641_add_uniqueness_of_variant_id_to_spree_stock_items.rb b/db/migrate/20180906094641_add_uniqueness_of_variant_id_to_spree_stock_items.rb new file mode 100644 index 0000000000..bc7713f428 --- /dev/null +++ b/db/migrate/20180906094641_add_uniqueness_of_variant_id_to_spree_stock_items.rb @@ -0,0 +1,5 @@ +class AddUniquenessOfVariantIdToSpreeStockItems < ActiveRecord::Migration + def change + add_index :spree_stock_items, :variant_id, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 1d7f167724..a93d5819f8 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20180812214434) do +ActiveRecord::Schema.define(:version => 20180906094641) do create_table "account_invoices", :force => true do |t| t.integer "user_id", :null => false @@ -961,6 +961,7 @@ ActiveRecord::Schema.define(:version => 20180812214434) do add_index "spree_stock_items", ["stock_location_id", "variant_id"], :name => "stock_item_by_loc_and_var_id" add_index "spree_stock_items", ["stock_location_id"], :name => "index_spree_stock_items_on_stock_location_id" + add_index "spree_stock_items", ["variant_id"], :name => "index_spree_stock_items_on_variant_id", :unique => true create_table "spree_stock_locations", :force => true do |t| t.string "name" diff --git a/lib/open_food_network/variant_stock.rb b/lib/open_food_network/variant_stock.rb index 98bde544f7..0b2773542d 100644 --- a/lib/open_food_network/variant_stock.rb +++ b/lib/open_food_network/variant_stock.rb @@ -98,7 +98,6 @@ module OpenFoodNetwork warn_deprecation(__method__, 'Spree::Config[:track_inventory_levels]') raise_error_if_no_stock_item_available - raise_error_if_multiple_stock_items # There should be only one at the default stock location. # @@ -126,11 +125,6 @@ module OpenFoodNetwork raise message if stock_items.empty? end - def raise_error_if_multiple_stock_items - message = 'A variant cannot have more than a stock item.' - raise message if stock_items.size > 1 - end - # Backwards compatible setting of stock levels in Spree 2.0. # It would be better to use `Spree::StockItem.adjust_count_on_hand` which # takes a value to add to the current stock level and uses proper locking.