From 6be60b0ae50d0458fd0c32a494f42e8dcf4d6126 Mon Sep 17 00:00:00 2001 From: Krzysztof Kotlarek Date: Tue, 13 Oct 2020 08:23:04 +1100 Subject: [PATCH] FEATURE: respect tags_sort_alphabetically setting when display tags (#10889) Currently, tag labels are displayed in random order. They should be displayed in alphabetical or popularity order based on SiteSetting (tags_sort_alphabetically) Meta: https://meta.discourse.org/t/how-to-apply-tag-sorts-by-popularity-to-topic-list-currently-it-seems-only-apply-to-tag-page/163186/7 --- app/serializers/concerns/topic_tags_mixin.rb | 3 ++- .../serializers/topic_view_serializer_spec.rb | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/app/serializers/concerns/topic_tags_mixin.rb b/app/serializers/concerns/topic_tags_mixin.rb index 58841188b07a7..990f8ad1f304e 100644 --- a/app/serializers/concerns/topic_tags_mixin.rb +++ b/app/serializers/concerns/topic_tags_mixin.rb @@ -11,7 +11,8 @@ def include_tags? def tags # Calling method `pluck` along with `includes` causing N+1 queries - tags = topic.tags.map(&:name) + order_setting = SiteSetting.tags_sort_alphabetically ? { name: :asc } : { topic_count: :desc } + tags = topic.tags.order(order_setting).map(&:name) if scope.is_staff? tags diff --git a/spec/serializers/topic_view_serializer_spec.rb b/spec/serializers/topic_view_serializer_spec.rb index 3262da29b5f8d..855dbc7d06ad0 100644 --- a/spec/serializers/topic_view_serializer_spec.rb +++ b/spec/serializers/topic_view_serializer_spec.rb @@ -212,6 +212,30 @@ def serialize_topic(topic, user_arg) end end + describe 'tags order' do + fab!(:tag1) { Fabricate(:tag, name: 'ctag', topic_count: 5) } + fab!(:tag2) { Fabricate(:tag, name: 'btag', topic_count: 9) } + fab!(:tag3) { Fabricate(:tag, name: 'atag', topic_count: 3) } + + before do + SiteSetting.tagging_enabled = true + topic.tags << tag1 + topic.tags << tag2 + topic.tags << tag3 + end + + it 'tags are automatically sorted by tag popularity' do + json = serialize_topic(topic, user) + expect(json[:tags]).to eq(%w(btag ctag atag)) + end + + it 'tags can be sorted alphabetically' do + SiteSetting.tags_sort_alphabetically = true + json = serialize_topic(topic, user) + expect(json[:tags]).to eq(%w(atag btag ctag)) + end + end + context "with flags" do fab!(:post) { Fabricate(:post, topic: topic) } fab!(:other_post) { Fabricate(:post, topic: topic) }