From f63b8bb79d7cc9060319037e5e641ffe123997b0 Mon Sep 17 00:00:00 2001 From: Bianca Nenciu Date: Thu, 6 Jun 2019 12:30:52 +0300 Subject: [PATCH] FIX: Periodically ensure consistency of categories. (#7663) --- app/jobs/scheduled/ensure_db_consistency.rb | 1 + app/models/category.rb | 9 +++++++++ lib/tasks/import.rake | 2 +- spec/models/category_spec.rb | 18 ++++++++++++++++++ 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/app/jobs/scheduled/ensure_db_consistency.rb b/app/jobs/scheduled/ensure_db_consistency.rb index de9f4e8cb67..dd85fa0b537 100644 --- a/app/jobs/scheduled/ensure_db_consistency.rb +++ b/app/jobs/scheduled/ensure_db_consistency.rb @@ -21,6 +21,7 @@ module Jobs CategoryTagStat.ensure_consistency! User.ensure_consistency! UserAvatar.ensure_consistency! + Category.ensure_consistency! end end end diff --git a/app/models/category.rb b/app/models/category.rb index 096ed96aba3..6dc5530e2b4 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -664,6 +664,15 @@ class Category < ActiveRecord::Base end end + def self.ensure_consistency! + Category + .joins('LEFT JOIN topics ON categories.topic_id = topics.id AND topics.deleted_at IS NULL') + .where({ topics: { id: nil }}) + .find_each do |category| + category.create_category_definition + end + end + private def check_permissions_compatibility(parent_permissions, child_permissions) diff --git a/lib/tasks/import.rake b/lib/tasks/import.rake index e54ed4260df..92c4b90a558 100644 --- a/lib/tasks/import.rake +++ b/lib/tasks/import.rake @@ -428,7 +428,7 @@ end def create_category_definitions log "Creating category definitions" - Category.where(topic_id: nil).each(&:create_category_definition) + Category.ensure_consistency! end def log(message) diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb index 39bce54d188..5746d396311 100644 --- a/spec/models/category_spec.rb +++ b/spec/models/category_spec.rb @@ -890,4 +890,22 @@ describe Category do end end + describe "#ensure_consistency!" do + it "creates category topic" do + category = Fabricate(:category) + category_destroyed = Fabricate(:category) + category_trashed = Fabricate(:category) + + category_topic_id = category.topic.id + category_destroyed.topic.destroy! + category_trashed.topic.trash! + + Category.ensure_consistency! + + expect(category.reload.topic_id).to eq(category_topic_id) + expect(category_destroyed.reload.topic).to_not eq(nil) + expect(category_trashed.reload.topic).to_not eq(nil) + end + end + end