DEV: Avoid nil custom fields (#28)

DEV: Avoid nil custom fields (#28)

diff --git a/db/post_migrate/20210429154320_remove_nil_custom_fields_from_category_experts.rb b/db/post_migrate/20210429154320_remove_nil_custom_fields_from_category_experts.rb
new file mode 100644
index 0000000..290eafd
--- /dev/null
+++ b/db/post_migrate/20210429154320_remove_nil_custom_fields_from_category_experts.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+class RemoveNilCustomFieldsFromCategoryExperts < ActiveRecord::Migration[6.0]
+  def up
+    execute <<~SQL
+      DELETE FROM post_custom_fields
+      WHERE name = 'category_expert_post' AND value IS NULL
+    SQL
+  end
+
+  def down
+    raise ActiveRecord::IrreversibleMigration
+  end
+end
diff --git a/lib/category_experts/post_handler.rb b/lib/category_experts/post_handler.rb
index 86d35e2..30b2834 100644
--- a/lib/category_experts/post_handler.rb
+++ b/lib/category_experts/post_handler.rb
@@ -22,20 +22,25 @@ module CategoryExperts
 
       post_group_name = post.custom_fields[CategoryExperts::POST_APPROVED_GROUP_NAME]
 
-      post.custom_fields[CategoryExperts::POST_APPROVED_GROUP_NAME] = nil
+      post.custom_fields.delete(CategoryExperts::POST_APPROVED_GROUP_NAME)
       post.custom_fields[CategoryExperts::POST_PENDING_EXPERT_APPROVAL] = true
       post.save!
 
       topic = post.topic
-      has_accepted_posts_from_same_group = PostCustomField.where(
+      has_accepted_posts_from_same_group = post_group_name && PostCustomField.where(
         post_id: topic.post_ids,
         name: CategoryExperts::POST_APPROVED_GROUP_NAME,
         value: post_group_name
       ).exists?
 
       unless has_accepted_posts_from_same_group
-        topic.custom_fields[CategoryExperts::TOPIC_EXPERT_POST_GROUP_NAMES] =
-          ((topic.custom_fields[CategoryExperts::TOPIC_EXPERT_POST_GROUP_NAMES]&.split("|") || []) - [post_group_name]).join("|")
+        groups = (topic.custom_fields[CategoryExperts::TOPIC_EXPERT_POST_GROUP_NAMES]&.split("|") || []) - [post_group_name]
+
+        if groups.any?
+          topic.custom_fields[CategoryExperts::TOPIC_EXPERT_POST_GROUP_NAMES] = groups.join("|")
+        else
+          topic.custom_fields.delete(CategoryExperts::TOPIC_EXPERT_POST_GROUP_NAMES)
+        end
       end
 
       topic.custom_fields[CategoryExperts::TOPIC_NEEDS_EXPERT_POST_APPROVAL] =
@@ -47,7 +52,7 @@ module CategoryExperts
       raise Discourse::InvalidParameters unless ensure_poster_is_category_expert
 
       post.custom_fields[CategoryExperts::POST_APPROVED_GROUP_NAME] = users_expert_group.name
-      post.custom_fields[CategoryExperts::POST_PENDING_EXPERT_APPROVAL] = nil
+      post.custom_fields[CategoryExperts::POST_PENDING_EXPERT_APPROVAL] = false
       post.save!
 
       topic = post.topic

GitHub sha: 27c22587

This commit appears in #28 which was approved by eviltrout and markvanlan. It was merged by CvX.