Skip to content

Commit

Permalink
Use none? instead of count.zero?
Browse files Browse the repository at this point in the history
`taggings.count.zero?` executes the following sql
`SELECT COUNT(*) FROM taggings WHERE taggings.tag_id = ?`

This can be very slow on large tables by using
`taggings.none?` it instead executes:
`SELECT 1 AS one FROM taggings WHERE taggings.tag_id = 304185392 LIMIT 1`

which can always use the primary key index and is much faster.
  • Loading branch information
gr-eg committed Apr 9, 2021
1 parent 509a3e6 commit 426d960
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/acts_as_taggable_on/tagging.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def remove_unused_tags
if ActsAsTaggableOn.tags_counter
tag.destroy if tag.reload.taggings_count.zero?
else
tag.destroy if tag.reload.taggings.count.zero?
tag.destroy if tag.reload.taggings.none?
end
end
end
Expand Down
16 changes: 16 additions & 0 deletions spec/acts_as_taggable_on/tagging_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@
ActsAsTaggableOn.remove_unused_tags = previous_setting
end

it 'should destroy unused tags after tagging destroyed when not using tags_counter' do
remove_unused_tags_previous_setting = ActsAsTaggableOn.remove_unused_tags
tags_counter_previous_setting = ActsAsTaggableOn.tags_counter
ActsAsTaggableOn.remove_unused_tags = true
ActsAsTaggableOn.tags_counter = false

ActsAsTaggableOn::Tag.destroy_all
@taggable = TaggableModel.create(name: 'Bob Jones')
@taggable.update_attribute :tag_list, 'aaa,bbb,ccc'
@taggable.update_attribute :tag_list, ''
expect(ActsAsTaggableOn::Tag.count).to eql(0)

ActsAsTaggableOn.remove_unused_tags = remove_unused_tags_previous_setting
ActsAsTaggableOn.tags_counter = tags_counter_previous_setting
end

describe 'context scopes' do
before do
@tagging_2 = ActsAsTaggableOn::Tagging.new
Expand Down

0 comments on commit 426d960

Please sign in to comment.