Skip to content

Commit dafd019

Browse files
committed
Add a description of locate_many / locate_many_signed
1 parent 1d27840 commit dafd019

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

README.md

+27
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,33 @@ GlobalID::Locator.locate_signed(#_person_sgid.to_s, for: '#_form')
133133
# => #<Person:0x007fae94bf6298 @id="1">
134134
```
135135

136+
### Retrieving a collection of GlobalIDs
137+
138+
It's possible that you have a collection of Global ID's, perhaps passed as parameters in a controller. Naively, calling `GlobalID::Locator.locate` for each Global ID in a collection will initiate an SQL select query `n` times (which can be a performance hit)
139+
140+
Instead, use `GlobalID::Locator.locate_many` (and its counterpart `GlobalID::Locator.locate_many_signed`) to retrieve a collection using the minimum number of SQL queries necessary. It uses just one query per model class.
141+
142+
```ruby
143+
ids = (User.first(3) + Student.first(3)).sort_by(&:id).map(&:to_global_id)
144+
# => [#<GlobalID:0x00007ffd6a8411a0 @uri=#<URI::GID gid://app/User/1>>,
145+
#<GlobalID:0x00007ffd675d32b8 @uri=#<URI::GID gid://app/Student/1>>,
146+
#<GlobalID:0x00007ffd6a840b10 @uri=#<URI::GID gid://app/User/2>>,
147+
#<GlobalID:0x00007ffd675d2c28 @uri=#<URI::GID gid://app/Student/2>>,
148+
#<GlobalID:0x00007ffd6a840480 @uri=#<URI::GID gid://app/User/3>>,
149+
#<GlobalID:0x00007ffd675d2598 @uri=#<URI::GID gid://app/Student/3>>]
150+
151+
objects = GlobalID::Locator.locate_many ids
152+
# SELECT "users".*
153+
# FROM "users"
154+
# WHERE "users"."id" IN ($1, $2, $3) [["id", 1], ["id", 2], ["id", 3]]
155+
# SELECT "students".*
156+
# FROM "students"
157+
# WHERE "students"."id" IN ($1, $2, $3) [["id", 1], ["id", 2], ["id", 3]]
158+
# => [#<User id: 1>, #<Student id: 1>, #<User id: 2>, #<Student id: 2>, #<User id: 3>, #<Student id: 3>]
159+
```
160+
161+
Notice how using `locate_many` has only used 2 SQL queries (one for all the Users, one for all the Students), and has maintained the order of the items in the collection.
162+
136163
### Custom App Locator
137164

138165
A custom locator can be set for an app by calling `GlobalID::Locator.use` and providing an app locator to use for that app.

0 commit comments

Comments
 (0)