Skip to content

Commit

Permalink
Fix defect where aliased attribute methods on abstract classes were b…
Browse files Browse the repository at this point in the history
…eing not defined

rails/rails@a88f47d fixed an issue where subclasses were regenerating aliased attribute methods defined on parent classes. Part of the solution was to call #generate_alias_attributes recursively on a class's superclass to generate all the alias attributes in the inheritance hierarchy. However, the implementation relies on #base_class to determine if we should call #generate_alias_attributes on the superclass. Since all models that inherit from abstract classes are base classes, this means that #generate_alias_attributes will never be called on abstract classes, meaning no method will be generated for any alias attributes defined on them.

To fix this issue, we should always call #generate_alias_attributes on the superclass unless the superclass is ActiveRecord::Base.
  • Loading branch information
andrewn617 committed Aug 21, 2023
1 parent bef4c69 commit 211146b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/attribute_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def eagerly_generate_alias_attribute_methods(_new_name, _old_name) # :nodoc:
end

def generate_alias_attributes # :nodoc:
superclass.generate_alias_attributes unless base_class?
superclass.generate_alias_attributes unless superclass == Base
return if @alias_attributes_mass_generated

generated_attribute_methods.synchronize do
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/attribute_methods_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,18 @@ class ChildWithDeprecatedBehaviorResolved < ClassWithDeprecatedAliasAttributeBeh
assert_equal("overridden_subject_was", obj.subject_was)
end

test "#alias_attribute method on an abstract class is available on subclasses" do
superclass = Class.new(ActiveRecord::Base) do
self.abstract_class = true
alias_attribute :id_value, :id
end
subclass = Class.new(superclass) { self.table_name = "topics" }

object = subclass.build(id: 123_456)

assert_equal 123_456, object.id_value
end

private
def new_topic_like_ar_class(&block)
klass = Class.new(ActiveRecord::Base) do
Expand Down

0 comments on commit 211146b

Please sign in to comment.