Skip to content

Commit 759d1eb

Browse files
committed
Don't break on models where primary_key is not defined
1 parent 27dff72 commit 759d1eb

3 files changed

Lines changed: 47 additions & 2 deletions

File tree

lib/global_id/locator.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -190,14 +190,18 @@ def find_records(model_class, ids, options)
190190
model_class = model_class.includes(options[:includes]) if options[:includes]
191191

192192
if options[:ignore_missing]
193-
model_class.where(model_class.primary_key => ids)
193+
model_class.where(primary_key(model_class) => ids)
194194
else
195195
model_class.find(ids)
196196
end
197197
end
198198

199199
def model_id_is_valid?(gid)
200-
Array(gid.model_id).size == Array(gid.model_class.primary_key).size
200+
Array(gid.model_id).size == Array(primary_key(gid.model_class)).size
201+
end
202+
203+
def primary_key(model_class)
204+
model_class.respond_to?(:primary_key) ? model_class.primary_key : :id
201205
end
202206
end
203207

test/cases/global_locator_test.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,23 @@ def locate_many(gids, options = {}); gids.map(&:model_id); end
369369
end
370370
end
371371

372+
test 'by GID without a primary key method' do
373+
model = PersonWithoutPrimaryKey.new('id')
374+
gid = model.to_gid
375+
model2 = PersonWithoutPrimaryKey.new('id2')
376+
gid2 = model.to_gid
377+
378+
found = GlobalID::Locator.locate(gid)
379+
assert_kind_of model.class, found
380+
assert_equal 'id', found.id
381+
382+
found = GlobalID::Locator.locate_many([gid, gid2])
383+
assert_equal 2, found.length
384+
385+
found = GlobalID::Locator.locate_many([gid, gid2], ignore_missing: true)
386+
assert_equal 2, found.length
387+
end
388+
372389
private
373390
def with_app(app)
374391
old_app, GlobalID.app = GlobalID.app, app

test/models/person.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,27 @@ def ==(other)
101101
other.is_a?(self.class) && id == other.try(:id) && parent == other.parent
102102
end
103103
end
104+
105+
class PersonWithoutPrimaryKey
106+
include GlobalID::Identification
107+
108+
attr_reader :id
109+
110+
def self.find(id_or_ids)
111+
if id_or_ids.is_a? Array
112+
ids = id_or_ids
113+
ids.collect { |id| find(id) }
114+
else
115+
id = id_or_ids
116+
new(id)
117+
end
118+
end
119+
120+
def self.where(conditions)
121+
(conditions[:id]).collect { |id| new(id) }
122+
end
123+
124+
def initialize(id = 1)
125+
@id = id
126+
end
127+
end

0 commit comments

Comments
 (0)