Skip to content

Commit d51fa84

Browse files
Merge pull request rails#49109 from Shopify/document-find-with-cpk
[Docs] Document using `FinderMethods.find` on composite primary key models
2 parents 5504c22 + 0aa4cc4 commit d51fa84

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

activerecord/lib/active_record/relation/finder_methods.rb

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ module ActiveRecord
66
module FinderMethods
77
ONE_AS_ONE = "1 AS one"
88

9-
# Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
9+
# Find by id - This can either be a specific id (ID), a list of ids (ID, ID, ID), or an array of ids ([ID, ID, ID]).
10+
# `ID` refers to an "identifier". For models with a single-column primary key, `ID` will be a single value,
11+
# and for models with a composite primary key, it will be an array of values.
1012
# If one or more records cannot be found for the requested ids, then ActiveRecord::RecordNotFound will be raised.
1113
# If the primary key is an integer, find by id coerces its arguments by using +to_i+.
1214
#
@@ -18,6 +20,27 @@ module FinderMethods
1820
# Person.find([1]) # returns an array for the object with ID = 1
1921
# Person.where("administrator = 1").order("created_on DESC").find(1)
2022
#
23+
# ==== Find a record for a composite primary key model
24+
# TravelRoute.primary_key = [:origin, :destination]
25+
#
26+
# TravelRoute.find(["Ottawa", "London"])
27+
# => #<TravelRoute origin: "Ottawa", destination: "London">
28+
#
29+
# TravelRoute.find([["Paris", "Montreal"]])
30+
# => [#<TravelRoute origin: "Paris", destination: "Montreal">]
31+
#
32+
# TravelRoute.find(["New York", "Las Vegas"], ["New York", "Portland"])
33+
# => [
34+
# #<TravelRoute origin: "New York", destination: "Las Vegas">,
35+
# #<TravelRoute origin: "New York", destination: "Portland">
36+
# ]
37+
#
38+
# TravelRoute.find([["Berlin", "London"], ["Barcelona", "Lisbon"]])
39+
# => [
40+
# #<TravelRoute origin: "Berlin", destination: "London">,
41+
# #<TravelRoute origin: "Barcelona", destination: "Lisbon">
42+
# ]
43+
#
2144
# NOTE: The returned records are in the same order as the ids you provide.
2245
# If you want the results to be sorted by database, you can use ActiveRecord::QueryMethods#where
2346
# method and provide an explicit ActiveRecord::QueryMethods#order option.

0 commit comments

Comments
 (0)