Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't break on models where primary_key is not defined #168

Merged
merged 1 commit into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
17 changes: 17 additions & 0 deletions test/cases/global_locator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,23 @@ 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
model2 = PersonWithoutPrimaryKey.new('id2')
gid2 = model.to_gid

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

found = GlobalID::Locator.locate_many([gid, gid2])
assert_equal 2, found.length

found = GlobalID::Locator.locate_many([gid, gid2], ignore_missing: true)
assert_equal 2, found.length
end

private
def with_app(app)
old_app, GlobalID.app = GlobalID.app, app
Expand Down
24 changes: 24 additions & 0 deletions test/models/person.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,27 @@ 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_or_ids)
if id_or_ids.is_a? Array
ids = id_or_ids
ids.collect { |id| find(id) }
else
id = id_or_ids
new(id)
end
end

def self.where(conditions)
(conditions[:id]).collect { |id| new(id) }
end

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