Skip to content

Commit

Permalink
Don't break on models where primary_key is not defined
Browse files Browse the repository at this point in the history
  • Loading branch information
ghiculescu committed Sep 4, 2023
1 parent 27dff72 commit 2051832
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/global_id/locator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,18 @@ def find_records(model_class, ids, options)
model_class = model_class.includes(options[:includes]) if options[:includes]

if options[:ignore_missing]
model_class.where(model_class.primary_key => ids)
model_class.where(primary_key(model_class) => ids)
else
model_class.find(ids)
end
end

def model_id_is_valid?(gid)
Array(gid.model_id).size == Array(gid.model_class.primary_key).size
Array(gid.model_id).size == Array(primary_key(gid.model_class)).size
end

def primary_key(model_class)
model_class.respond_to?(:primary_key) ? model_class.primary_key : :id
end
end

Expand Down
9 changes: 9 additions & 0 deletions test/cases/global_locator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,15 @@ def locate_many(gids, options = {}); gids.map(&:model_id); end
end
end

test 'by GID without a primary key method' do
model = PersonWithoutPrimaryKey.new('id')
gid = model.to_gid

found = GlobalID::Locator.locate(gid)
assert_kind_of model.class, found
assert_equal 'id', found.id
end

private
def with_app(app)
old_app, GlobalID.app = GlobalID.app, app
Expand Down
14 changes: 14 additions & 0 deletions test/models/person.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,17 @@ def ==(other)
other.is_a?(self.class) && id == other.try(:id) && parent == other.parent
end
end

class PersonWithoutPrimaryKey
include GlobalID::Identification

attr_reader :id

def self.find(id)
new(id)
end

def initialize(id = 1)
@id = id
end
end

0 comments on commit 2051832

Please sign in to comment.