Merge pull request #51925 from zzak/re-51395-proxy_association

Make CollectionProxy#proxy_association public API
This commit is contained in:
Rafael Mendonça França 2024-05-28 13:39:28 -04:00 committed by GitHub
commit 809409ab29
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 20 additions and 1 deletions

View File

@ -928,7 +928,20 @@ module ActiveRecord
!!@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

View File

@ -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