Skip to content

Commit

Permalink
Make CollectionProxy#proxy_association public API
Browse files Browse the repository at this point in the history
Co-authored-by: Petrik <[email protected]>
  • Loading branch information
zzak and p8 committed May 27, 2024
1 parent a658c68 commit 7aa7e1e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
15 changes: 14 additions & 1 deletion activerecord/lib/active_record/associations/collection_proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -928,7 +928,20 @@ def include?(record)
!!@association.include?(record)
end

def proxy_association # :nodoc:
# Returns the association object for the collection.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.proxy_association
# # => #<ActiveRecord::Associations::HasManyAssociation owner="#<Person:0x00>">
#
# Returns the same object as <tt>person.association(:pets)</tt>,
# allowing you to make calls like <tt>person.pets.proxy_association.owner</tt>.
#
# See Associations::ClassMethods@Association+extensions for more.
def proxy_association
@association
end

Expand Down
6 changes: 6 additions & 0 deletions guides/source/association_basics.md
Original file line number Diff line number Diff line change
Expand Up @@ -2827,6 +2827,12 @@ class Supplier < ApplicationRecord
end
```

Extensions can refer to the internals of the association proxy using these three attributes of the `proxy_association` accessor:

* `proxy_association.owner` returns the object that the association is a part of.
* `proxy_association.reflection` returns the reflection object that describes the association.
* `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`.

### Association Scoping using the Association Owner

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

0 comments on commit 7aa7e1e

Please sign in to comment.