From d64853dfa09fbda202b8d335f023cb57dc52d00d Mon Sep 17 00:00:00 2001 From: Arpit Jalan Date: Thu, 28 Sep 2017 22:04:19 +0530 Subject: [PATCH] FIX: update group.has_messages field weekly --- app/models/group.rb | 13 +++++++++++++ spec/models/group_spec.rb | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/app/models/group.rb b/app/models/group.rb index 326d89781ab..d569c2e2898 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -308,6 +308,7 @@ class Group < ActiveRecord::Base def self.ensure_consistency! reset_all_counters! refresh_automatic_groups! + refresh_has_messages! end def self.reset_all_counters! @@ -331,6 +332,18 @@ class Group < ActiveRecord::Base args.each { |group| refresh_automatic_group!(group) } end + def self.refresh_has_messages! + exec_sql <<-SQL + UPDATE groups g SET has_messages = false + WHERE NOT EXISTS (SELECT tg.id + FROM topic_allowed_groups tg + INNER JOIN topics t ON t.id = tg.topic_id + WHERE tg.group_id = g.id + AND t.deleted_at IS NULL) + AND g.has_messages = true + SQL + end + def self.ensure_automatic_groups! AUTO_GROUPS.each_key do |name| refresh_automatic_group!(name) unless lookup_group(name) diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb index 9eee947198b..3920a7da43c 100644 --- a/spec/models/group_spec.rb +++ b/spec/models/group_spec.rb @@ -577,4 +577,21 @@ describe Group do expect(group.group_users.map(&:user_id)).to contain_exactly(user.id, admin.id) end end + + it "Correctly updates has_messages" do + group = Fabricate(:group, has_messages: true) + topic = Fabricate(:private_message_topic) + + # when group message is not present + Group.refresh_has_messages! + group.reload + expect(group.has_messages?).to eq false + + # when group message is present + group.update!(has_messages: true) + TopicAllowedGroup.create!(topic_id: topic.id, group_id: group.id) + Group.refresh_has_messages! + group.reload + expect(group.has_messages?).to eq true + end end