Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix re-using slugs from history on the same record (#13329)

Łukasz Adamczyk1f481151c5dc
diff --git a/core/lib/friendly_id/history_decorator.rb b/core/lib/friendly_id/history_decorator.rb
new file mode 100644
index 0000000000..a12698c908
--- /dev/null
+++ b/core/lib/friendly_id/history_decorator.rb
@@ -0,0 +1,26 @@
+module FriendlyId
+ module HistoryDecorator
+ private
+
+ # This a patch to friendly_id history module.
+ # Originally, it removes and re-creates a slug record if it already exists. The issue is that we use `acts_as_paranoid`
+ # for slugs so it sets the `deleted_at` timestamp instead of deleting the record. We need to delete the record instead.
+ def create_slug
+ return unless friendly_id
+ return if history_is_up_to_date?
+ # Allow reversion back to a previously used slug
+ relation = slugs.where(slug: friendly_id)
+ if friendly_id_config.uses?(:scoped)
+ relation = relation.where(scope: serialized_scope)
+ end
+ # Use `delete_all` instead of `destroy_all` to avoid the unique index error.
+ relation.delete_all unless relation.empty?
+ slugs.create! do |record|
+ record.slug = friendly_id
+ record.scope = serialized_scope if friendly_id_config.uses?(:scoped)
+ end
+ end
+ end
+end
+
+FriendlyId::History.prepend(FriendlyId::HistoryDecorator)
diff --git a/core/lib/spree_core.rb b/core/lib/spree_core.rb
index 81fde8f250..d57d8d32d5 100644
--- a/core/lib/spree_core.rb
+++ b/core/lib/spree_core.rb
@@ -1,4 +1,5 @@
require 'friendly_id/paranoia'
+require 'friendly_id/history_decorator'
require 'mobility/plugins/store_based_fallbacks'
require 'normalize_string'
diff --git a/core/spec/models/spree/product/slugs_spec.rb b/core/spec/models/spree/product/slugs_spec.rb
index 1c6393a0ca..9c5d0149f2 100644
--- a/core/spec/models/spree/product/slugs_spec.rb
+++ b/core/spec/models/spree/product/slugs_spec.rb
@@ -26,6 +26,15 @@ describe Spree::Product::Slugs, type: :model do
it 'soft deletes slug record' do
expect { product.destroy! }.to change { product.slugs.with_deleted.first.deleted? }.to be_truthy
end
+
+ it 'allows re-using the slug from history' do
+ previous_slug = product.slugs.where.not(slug: product.slug).first.slug
+ product.update!(slug: previous_slug)
+
+ expect(product.slug).to eq(previous_slug)
+ expect(product.slugs.count).to eq(2)
+ expect(product.slugs.first.slug).to eq(previous_slug)
+ end
end
describe 'ability to retake a slug of deleted record with the same name' do