Skip to content

Commit 0f8377d

Browse files
authored
Merge pull request rails#49153 from Shopify/ar_querying_guide_cpk_example
Active Record querying guide: add a composite primary key example for find
2 parents 6633671 + 351f055 commit 0f8377d

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

guides/source/active_record_querying.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,33 @@ SELECT * FROM customers WHERE (customers.id IN (1,10))
199199

200200
WARNING: The `find` method will raise an `ActiveRecord::RecordNotFound` exception unless a matching record is found for **all** of the supplied primary keys.
201201

202-
If your table uses a composite primary key, you'll need to pass an array to find a single item. You can also pass an array of arrays to find multiple records.
202+
If your table uses a composite primary key, you'll need to pass find an array to find a single item. For instance, if customers were defined with [:store_id, :id] as a primary key:
203+
204+
```irb
205+
# Find the customer with store_id 3 and id 17
206+
irb> customers = Customer.find([3, 17])
207+
=> #<Customer store_id: 3, id: 17, first_name: "Magda">
208+
```
209+
210+
The SQL equivalent of the above is:
211+
212+
```sql
213+
SELECT * FROM customers WHERE store_id = 3 AND id = 17
214+
```
215+
216+
To find multiple customers with composite IDs, you would pass an array of arrays:
217+
218+
```irb
219+
# Find the customers with primary keys [1, 8] and [7, 15].
220+
irb> customers = Customer.find([[1, 8], [7, 15]]) # OR Customer.find([1, 8], [7, 15])
221+
=> [#<Customer store_id: 1, id: 8, first_name: "Pat">, #<Customer store_id: 7, id: 15, first_name: "Chris">]
222+
```
223+
224+
The SQL equivalent of the above is:
225+
226+
```sql
227+
SELECT * FROM customers WHERE (store_id = 1 AND id = 8 OR store_id = 7 AND id = 15)
228+
```
203229

204230
#### `take`
205231

0 commit comments

Comments
 (0)