Skip to content

Commit 809409a

Browse files
authored
Merge pull request rails#51925 from zzak/re-51395-proxy_association
Make CollectionProxy#proxy_association public API
2 parents 31b7b1e + 7aa7e1e commit 809409a

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

activerecord/lib/active_record/associations/collection_proxy.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -928,7 +928,20 @@ def include?(record)
928928
!!@association.include?(record)
929929
end
930930

931-
def proxy_association # :nodoc:
931+
# Returns the association object for the collection.
932+
#
933+
# class Person < ActiveRecord::Base
934+
# has_many :pets
935+
# end
936+
#
937+
# person.pets.proxy_association
938+
# # => #<ActiveRecord::Associations::HasManyAssociation owner="#<Person:0x00>">
939+
#
940+
# Returns the same object as <tt>person.association(:pets)</tt>,
941+
# allowing you to make calls like <tt>person.pets.proxy_association.owner</tt>.
942+
#
943+
# See Associations::ClassMethods@Association+extensions for more.
944+
def proxy_association
932945
@association
933946
end
934947

guides/source/association_basics.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2827,6 +2827,12 @@ class Supplier < ApplicationRecord
28272827
end
28282828
```
28292829

2830+
Extensions can refer to the internals of the association proxy using these three attributes of the `proxy_association` accessor:
2831+
2832+
* `proxy_association.owner` returns the object that the association is a part of.
2833+
* `proxy_association.reflection` returns the reflection object that describes the association.
2834+
* `proxy_association.target` returns the associated object for `belongs_to` or `has_one`, or the collection of associated objects for `has_many` or `has_and_belongs_to_many`.
2835+
28302836
### Association Scoping using the Association Owner
28312837

28322838
The owner of the association can be passed as a single argument to the scope

0 commit comments

Comments
 (0)