Skip to content

Commit 1633fd6

Browse files
authored
Merge pull request #1845 from codidact/0valt/caching
Fix N+1 query on tag_synonyms when loading lists of tags
2 parents 74c1416 + 75acd77 commit 1633fd6

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

app/controllers/tags_controller.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,16 @@ def index
1010
@tag_set = if params[:tag_set].present?
1111
TagSet.find(params[:tag_set])
1212
end
13+
1314
@tags = if params[:term].present?
1415
(@tag_set&.tags || Tag).search(params[:term])
1516
else
1617
(@tag_set&.tags || Tag.all).order(:name)
17-
end.includes(:tag_synonyms).paginate(page: params[:page], per_page: 50)
18+
end
19+
20+
@tags = @tags.list_includes
21+
.paginate(page: params[:page], per_page: 50)
22+
1823
respond_to do |format|
1924
format.json do
2025
render json: @tags.to_json(include: { tag_synonyms: { only: :name } })
@@ -38,7 +43,7 @@ def category
3843
@tag_set.tags.where(excerpt: ['', nil])
3944
else
4045
@tag_set.tags
41-
end
46+
end.list_includes
4247

4348
table = params[:hierarchical].present? ? 'tags_paths' : 'tags'
4449

app/models/tag.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ class Tag < ApplicationRecord
1818
validate :synonym_unique
1919
validates :name, uniqueness: { scope: [:tag_set_id], case_sensitive: false }
2020

21+
# scopes
22+
scope :list_includes, -> { includes(:tag_synonyms) }
23+
2124
# Fuzzy-searches tags by name, excerpt, and synonym name
2225
# @param term [String] search term
2326
# @return [ActiveRecord::Relation<Tag>]

0 commit comments

Comments
 (0)