From ec1e7e68c8286eb133ae412db289d3c77a2a24bb Mon Sep 17 00:00:00 2001
From: Coraline <coraline@idolhands.com>
Date: Wed, 4 Dec 2024 21:09:11 -0600
Subject: [PATCH] Fix issue with identity orphans

---
 app/models/identity.rb | 2 +-
 app/models/keyword.rb  | 2 +-
 app/models/response.rb | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/app/models/identity.rb b/app/models/identity.rb
index e4e565b..d7ff552 100644
--- a/app/models/identity.rb
+++ b/app/models/identity.rb
@@ -24,7 +24,7 @@ def self.orphans
   end
 
   def self.reap_orphans
-    Identity.orphans.each(&:destroy)
+    query_as(:i).with('i, count{(i)-[:IDENTIFIES_WITH]-(:Persona)} AS ct').where('ct = 0').return('i, ct').map(&:first).each(&:destroy)
   end
 
   private
diff --git a/app/models/keyword.rb b/app/models/keyword.rb
index 7525c3e..bcac715 100644
--- a/app/models/keyword.rb
+++ b/app/models/keyword.rb
@@ -11,7 +11,7 @@ class Keyword
   validates :name, presence: true
   validates :name, uniqueness: true
 
-  has_many :in, :personas, rel_class: :ReflectsOn, dependent: :delete_orphans
+  has_many :in, :personas, rel_class: :ReflectsOn
 
   # This is the prompt passed to the AI agent to serve as instructions for extracting Keywords.
   PROMPT = %{
diff --git a/app/models/response.rb b/app/models/response.rb
index 288a584..8844065 100644
--- a/app/models/response.rb
+++ b/app/models/response.rb
@@ -6,7 +6,7 @@ class Response < ApplicationRecord
   belongs_to :question
 
   def codes
-    @codes ||= Code.where(name: self.raw_codes)
+    @codes ||= Code.where(name: self.raw_codes, context: self.question.context.name)
   end
 
   def sync_to_graph