FIX: `SearcLog.term_details` generating incorrect data because of case.

FIX: SearcLog.term_details generating incorrect data because of case.

Also match on equality rather than “LIKE ?” which is quite strange.

diff --git a/app/models/search_log.rb b/app/models/search_log.rb
index d046dae..152d6b5 100644
--- a/app/models/search_log.rb
+++ b/app/models/search_log.rb
@@ -87,13 +87,15 @@ class SearchLog < ActiveRecord::Base
     details = []
 
     result = SearchLog.select("COUNT(*) AS count, created_at::date AS date")
-      .where('term LIKE ?', term)
-      .where('created_at > ?', start_of(period))
+      .where(
+        'lower(term) = ? AND created_at > ?',
+        term.downcase, start_of(period)
+      )
 
     result = result.where('search_type = ?', search_types[search_type]) if search_type == :header || search_type == :full_page
     result = result.where('search_result_id IS NOT NULL') if search_type == :click_through_only
 
-    result.group(:term)
+    result
       .order("date")
       .group("date")
       .each do |record|
diff --git a/spec/models/search_log_spec.rb b/spec/models/search_log_spec.rb
index c98dda0..952b890 100644
--- a/spec/models/search_log_spec.rb
+++ b/spec/models/search_log_spec.rb
@@ -161,11 +161,17 @@ RSpec.describe SearchLog, type: :model do
     end
   end
 
-  context "term_details" do
+  describe ".term_details" do
     before do
       SearchLog.log(term: "ruby", search_type: :header, ip_address: "127.0.0.1")
-      SearchLog.log(term: 'ruby', search_type: :header, ip_address: '127.0.0.1', user_id: Fabricate(:user).id)
-      SearchLog.log(term: "ruby", search_type: :full_page, ip_address: "127.0.0.2")
+      SearchLog.log(term: 'rUby', search_type: :header, ip_address: '127.0.0.1', user_id: Fabricate(:user).id)
+      SearchLog.log(term: "ruBy", search_type: :full_page, ip_address: "127.0.0.2")
+
+      SearchLog.log(
+        term: "ruby core",
+        search_type: :header,
+        ip_address: "127.0.0.3"
+      )
     end
 
     it "correctly returns term details" do
@@ -175,7 +181,11 @@ RSpec.describe SearchLog, type: :model do
       term_header_details = SearchLog.term_details("ruby", :all, :header)
       expect(term_header_details[:data][0][:y]).to eq(2)
 
-      SearchLog.where(term: 'ruby', ip_address: '127.0.0.2').update_all(search_result_id: 24)
+      SearchLog
+        .where("lower(term) = ?", 'ruby')
+        .where(ip_address: '127.0.0.2')
+        .update_all(search_result_id: 24)
+
       term_click_through_details = SearchLog.term_details("ruby", :all, :click_through_only)
       expect(term_click_through_details[:period]).to eq("all")
       expect(term_click_through_details[:data][0][:y]).to eq(1)

GitHub sha: d8faf5f7