Skip to content

Pass associations added to a parent down to existing subclasses - #59462

Merged
tenderlove merged 1 commit into
rails:mainfrom
jasonmaxlee:subclass-inherits-later-parent-associations
Oct 31, 2026
Merged

tenderlove merged 1 commit into
rails:mainfrom
jasonmaxlee:subclass-inherits-later-parent-associations

Conversation

@jasonmaxlee

Copy link
Copy Markdown
Contributor

Motivation / Background

Fixes #20678

If a subclass defines an association of its own, and an association is added to its parent afterwards (an engine, a concern, or a reopened class loaded later), the subclass has the reader method but calling it raises:

class Post < ActiveRecord::Base; end
class FancyPost < Post
  has_many :tags
end
Post.has_many :comments

FancyPost.first.comments
# => ActiveRecord::AssociationNotFoundError: Association named 'comments' was not found on FancyPost

add_reflection writes a new frozen _reflections hash to the defining class. FancyPost got its own copy when it defined tags, so it never sees comments. A subclass that only inherits the hash can also keep a stale normalized_reflections cache if it read its reflections before the parent changed.

Detail

This Pull Request makes add_reflection walk the class's descendants after adding a reflection. It clears each descendant's reflection cache, and adds the new reflection to every descendant that holds its own copy, unless that descendant (or a class between it and the parent) defines an association with the same name, in which case the override is kept.

This is the approach sgrif and matthewd suggested in the review of #24719, which stalled in 2016.

Additional information

Tests in reflection_test.rb:

  • a subclass with its own association gets the parent's later one, and loads exactly its own comment rows through it
  • the same for a grandchild
  • a subclass that only inherits, but read its reflections first, sees the new one (stale cache)
  • a subclass that overrides the same association name keeps its own reflection

The first three failed before the change (the subclass reflection was nil) and pass after. The override test passed before and after, so the existing behavior is preserved. The full Active Record SQLite suite passes.

descendants is only non-empty when an association is added after subclasses exist, so normal class loading (parent first) does no extra work.

Checklist

  • This Pull Request is related to one change. Unrelated changes should be opened in separate PRs.
  • Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • Tests are added or updated if you fix a bug or add a feature.
  • CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.

`add_reflection` writes a new frozen `_reflections` hash to the class
that defines the association. A subclass that had already defined an
association of its own holds its own copy, so an association added to
the parent afterwards never reaches it: the generated reader exists on
the subclass, but `association` can't find the reflection and raises
`AssociationNotFoundError`. Subclasses that only inherit the hash can
also keep a stale `normalized_reflections` cache.

When a reflection is added, walk the class's descendants, clear their
caches, and add it to each one that has its own copy, unless that
subclass (or a class between it and the parent) defines the same name.

This follows the direction from the review of rails#24719.

Fix rails#20678
@tenderlove
tenderlove merged commit a80ce9f into rails:main Oct 31, 2026
4 checks passed
kamipo pushed a commit to kehra/rails that referenced this pull request Nov 1, 2026
`add_aggregate_reflection` writes a new frozen `aggregate_reflections`
hash to the class that calls `composed_of`. A subclass that had already
defined an aggregation of its own holds its own copy, so an aggregation
added to the parent afterwards never reaches it: the reader and writer
are inherited, but `reflect_on_aggregation` returns `nil`, and `where`
on the subclass doesn't expand the value object into its mapped columns,
so `where(balance: Money.new(5))` passes the `Money` object to the
database as is and typically raises `TypeError`.

Walk the class's descendants like `add_reflection` does for
associations since rails#59462, and add the aggregation to each subclass
that has its own copy, unless that subclass defines the same name.
kamipo pushed a commit to kehra/rails that referenced this pull request Nov 1, 2026
`attr_readonly` writes a new `_attr_readonly` array to the class that
calls it. A subclass that had already declared readonly attributes of its
own holds its own copy, so attributes declared readonly on the parent
afterwards never reach it: `readonly_attributes` on the subclass doesn't
include them, and they can be assigned and saved on its records without
`ActiveRecord::ReadonlyAttributeError`.

Walk the class's descendants like `add_reflection` does for associations
since rails#59462, and add the attributes to each subclass that has its own
copy.
kamipo pushed a commit that referenced this pull request Nov 1, 2026
`alias_attribute` writes a new frozen `attribute_aliases` hash to the class
that calls it. A subclass that already holds its own copy never sees an
alias added to the parent afterwards. A subclass gets its own copy when it
defines an alias of its own, and in Active Record also when its attribute
methods are generated under an abstract class, since that adds the
`id_value` entry to its hash.

The alias methods are inherited, but `attribute_alias?` returns `false`,
and in Active Record `where(headline: "a")` on the subclass uses `headline`
as a column name and raises `ActiveRecord::StatementInvalid`.

Walk the class's descendants like `add_reflection` does for associations
since #59462, and add the alias to each subclass that has its own copy,
unless that subclass already has an alias with that name.
yahonda added a commit that referenced this pull request Nov 17, 2026
Follow up #59462

`ReflectionTest#test_association_added_to_parent_reaches_subclass_that_defined_its_own_first`
creates a post and expects only the two comments it creates for that
post. `ReflectionTest` does not load the `posts` and `comments`
fixtures. When an earlier test class has loaded `comments` but not
`posts`, the new post gets id 1 and the fixture comments 1 and 2, whose
`post_id` is 1, are returned as well.

Load both fixtures so that the new post never gets the id of a post in
the fixtures.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Subclass misses association defined on parent

2 participants