Skip to content

Commit

Permalink
Fix: Adding a new property with the same name to a product omits vali…
Browse files Browse the repository at this point in the history
…dation and throws error 'PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_spree_product_properties_on_property_id_and_product_id"'
  • Loading branch information
kgorazd committed Mar 18, 2022
1 parent 87d8228 commit 402e0dc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
19 changes: 18 additions & 1 deletion app/controllers/spree/admin/products_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def update
params[:product][:option_type_ids] = params[:product][:option_type_ids].reject(&:empty?)
end
invoke_callbacks(:update, :before)
if @object.update(permitted_resource_params)
if @object.update(sanitized_resource_params)
set_current_store
invoke_callbacks(:update, :after)
flash[:success] = flash_message_for(@object, :successfully_updated)
Expand Down Expand Up @@ -196,6 +196,23 @@ def permitted_resource_params
end
end

def sanitized_resource_params
return permitted_resource_params if permitted_resource_params[:product_properties_attributes].nil?

taken_property_names = []
unique_product_properties_attributes = permitted_resource_params[:product_properties_attributes].select do |_, property_attributes|
if taken_property_names.include?(property_attributes[:property_name])
false
else
taken_property_names << property_attributes[:property_name]
true
end
end
sanitized_resource_params = permitted_resource_params
sanitized_resource_params[:product_properties_attributes] = unique_product_properties_attributes
sanitized_resource_params
end

private

def variant_stock_includes
Expand Down
9 changes: 9 additions & 0 deletions spec/controllers/spree/admin/products_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@
expect(flash[:success]).to eq("Product #{product.name.inspect} has been successfully updated!")
end
end

context 'adding the same property to a product twice' do
let(:product_params) { { product_properties_attributes: { '1' => { property_name: 'Foo', value: 'bar' }, '2' => { property_name: 'Foo', value: 'bar2' } } } }

specify do
expect { send_request }.not_to raise_error
expect(flash[:success]).to eq("Product #{product.name.inspect} has been successfully updated!")
end
end
end

# regression test for #801
Expand Down

0 comments on commit 402e0dc

Please sign in to comment.