Skip to content

Commit f360c13

Browse files
committed
Fix issue when reordering tags and @@remove_unused_tags is true
When reordering taggings, the taggings get deleted and recreated. However, by the time the taggings are recreated, the tags have already been removed. Fixed by wrapping the delete + create in a transaction, and only removing unused tags on transaction commit.
1 parent 25266d6 commit f360c13

3 files changed

Lines changed: 27 additions & 10 deletions

File tree

lib/acts-as-taggable-on/taggable/core.rb

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -275,15 +275,17 @@ def save_tags
275275
# Delete discarded tags and create new tags
276276
end
277277

278-
# Destroy old taggings:
279-
taggings.not_owned.by_context(context).where(tag_id: old_tags).destroy_all if old_tags.present?
280-
281-
# Create new taggings:
282-
new_tags.each do |tag|
283-
if taggable_tenant
284-
taggings.create!(tag_id: tag.id, context: context.to_s, taggable: self, tenant: taggable_tenant)
285-
else
286-
taggings.create!(tag_id: tag.id, context: context.to_s, taggable: self)
278+
transaction do
279+
# Destroy old taggings:
280+
taggings.not_owned.by_context(context).where(tag_id: old_tags).destroy_all if old_tags.present?
281+
282+
# Create new taggings:
283+
new_tags.each do |tag|
284+
if taggable_tenant
285+
taggings.create!(tag_id: tag.id, context: context.to_s, taggable: self, tenant: taggable_tenant)
286+
else
287+
taggings.create!(tag_id: tag.id, context: context.to_s, taggable: self)
288+
end
287289
end
288290
end
289291
end

lib/acts-as-taggable-on/tagging.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class Tagging < ActsAsTaggableOn.base_class.constantize # :nodoc:
2323

2424
validates_uniqueness_of :tag_id, scope: %i[taggable_type taggable_id context tagger_id tagger_type]
2525

26-
after_destroy :remove_unused_tags
26+
after_destroy_commit :remove_unused_tags
2727

2828
private
2929

spec/acts_as_taggable_on/taggable_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,21 @@
9292
ids = @taggable.tags.map { |t| t.taggings.first.id }
9393
expect(ids).to eq(ids.sort)
9494
end
95+
96+
it 'can reorder tags successfully when @@remove_unused_tags is true' do
97+
ActsAsTaggableOn.remove_unused_tags = true
98+
99+
@taggable.tag_list = 'pow, ruby, rails'
100+
@taggable.save!
101+
@taggable.reload
102+
expect(@taggable.tag_list).to eq(%w(pow ruby rails))
103+
104+
@taggable.tag_list = 'rails, pow, ruby'
105+
@taggable.save!
106+
@taggable.reload
107+
expect(@taggable.tag_list).to eq(%w(rails pow ruby))
108+
109+
end
95110
end
96111

97112
describe 'Taggable' do

0 commit comments

Comments
 (0)