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.
This commit is contained in:
Pau Perez
2018-09-06 13:16:20 +02:00
parent 8848af15ee
commit cd53ec1a4f
3 changed files with 7 additions and 7 deletions

View File

@@ -0,0 +1,5 @@
class AddUniquenessOfVariantIdToSpreeStockItems < ActiveRecord::Migration
def change
add_index :spree_stock_items, :variant_id, unique: true
end
end

View File

@@ -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"

View File

@@ -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.