From a0eecf98ad6d568e24d3324f8ad8b016352edbe5 Mon Sep 17 00:00:00 2001
From: Steve Lawson <steve.lawson@revolutionprep.com>
Date: Thu, 13 Sep 2012 13:48:19 -0700
Subject: [PATCH] Use ActiveRecord .primary_key instead of :id when building
 exclusion condition

Fixes: #194 - add_exclude_condition breaks on tables without ID field - https://github.com/alexreisner/geocoder/issues/194
---
 lib/geocoder/stores/active_record.rb |  2 +-
 test/active_record_test.rb           | 15 +++++++++++++++
 test/test_helper.rb                  | 25 +++++++++++++++++++++++++
 3 files changed, 41 insertions(+), 1 deletion(-)
 create mode 100644 test/active_record_test.rb

diff --git a/lib/geocoder/stores/active_record.rb b/lib/geocoder/stores/active_record.rb
index 96b11e07..8250623c 100644
--- a/lib/geocoder/stores/active_record.rb
+++ b/lib/geocoder/stores/active_record.rb
@@ -253,7 +253,7 @@ module Geocoder::Store
       #
       def add_exclude_condition(conditions, exclude)
         if exclude
-          conditions[0] << " AND #{full_column_name(:id)} != ?"
+          conditions[0] << " AND #{full_column_name(primary_key)} != ?"
           conditions << exclude.id
         end
         conditions
diff --git a/test/active_record_test.rb b/test/active_record_test.rb
new file mode 100644
index 00000000..6d2d2316
--- /dev/null
+++ b/test/active_record_test.rb
@@ -0,0 +1,15 @@
+# encoding: utf-8
+require 'test_helper'
+
+class ActiveRecordTest < Test::Unit::TestCase
+
+  def test_exclude_condition_when_model_has_a_custom_primary_key
+    venue = VenuePlus.new(*venue_params(:msg))
+
+    # just call private method directly so we don't have to stub .near scope
+    conditions = venue.class.send(:add_exclude_condition, ["fake_condition"], venue)
+
+    assert_match( /#{VenuePlus.primary_key}/, conditions.join)
+  end
+
+end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index 8ac6b3e0..e8329562 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -35,6 +35,17 @@ module ActiveRecord
         read_attribute name
       end
     end
+
+    class << self
+      def table_name
+        'test_table_name'
+      end
+
+      def primary_key
+        :id
+      end
+    end
+
   end
 end
 
@@ -192,6 +203,20 @@ class Venue < ActiveRecord::Base
   end
 end
 
+##
+# Geocoded model.
+# - Has user-defined primary key (not just 'id')
+#
+class VenuePlus < Venue
+
+  class << self
+    def primary_key
+      :custom_primary_key_id
+    end
+  end
+
+end
+
 ##
 # Reverse geocoded model.
 #
-- 
GitLab