DEV: Avoid nil custom fields (#24)

DEV: Avoid nil custom fields (#24)

diff --git a/db/post_migrate/20210429154321_remove_nil_custom_fields_from_policy.rb b/db/post_migrate/20210429154321_remove_nil_custom_fields_from_policy.rb
new file mode 100644
index 0000000..1d995f0
--- /dev/null
+++ b/db/post_migrate/20210429154321_remove_nil_custom_fields_from_policy.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+class RemoveNilCustomFieldsFromPolicy < ActiveRecord::Migration[6.0]
+  def up
+    execute <<~SQL
+      DELETE FROM post_custom_fields
+      WHERE name = 'HasPolicy' AND value IS NULL
+    SQL
+  end
+
+  def down
+    raise ActiveRecord::IrreversibleMigration
+  end
+end
diff --git a/plugin.rb b/plugin.rb
index e642c7e..7e5c035 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -169,7 +169,7 @@ after_initialize do
     end
 
     if !has_group && (post.custom_fields[DiscoursePolicy::HasPolicy] || !post_policy&.new_record?)
-      post.custom_fields[DiscoursePolicy::HasPolicy] = nil
+      post.custom_fields.delete(DiscoursePolicy::HasPolicy)
       post.save_custom_fields
       PostPolicy.where(post_id: post.id).destroy_all
     end

GitHub sha: 989f0b27

This commit appears in #24 which was approved by tgxworld. It was merged by CvX.