Skip to content

Commit 831810c

Browse files
authored
Merge pull request rails#50158 from fatkodima/fix-alias_attribute-sti
Fix defining `alias_attribute` for STI classes with abstract class in the inheritance chain
2 parents c60d064 + 3bdd595 commit 831810c

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

activerecord/lib/active_record/attribute_methods.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ def define_attribute_methods # :nodoc:
130130
return false if @attribute_methods_generated
131131
superclass.define_attribute_methods unless base_class?
132132
super(attribute_names)
133+
alias_attribute(:id_value, :id) if attribute_names.include?("id")
133134
@attribute_methods_generated = true
134135
end
135136
end

activerecord/lib/active_record/model_schema.rb

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,6 @@ def load_schema!
584584
columns_hash = connection.schema_cache.columns_hash(table_name)
585585
columns_hash = columns_hash.except(*ignored_columns) unless ignored_columns.empty?
586586
@columns_hash = columns_hash.freeze
587-
alias_attribute :id_value, :id if @columns_hash.key?("id")
588587
end
589588

590589
# Guesses the table name, but does not decorate it with prefix and suffix information.

activerecord/test/cases/attribute_methods_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1393,6 +1393,22 @@ class ChildWithDeprecatedBehaviorResolved < ClassWithDeprecatedAliasAttributeBeh
13931393
alias_attribute :written_by, :author
13941394
end
13951395

1396+
test "#alias_attribute method on a STI class is available on subclasses" do
1397+
superclass = Class.new(ActiveRecord::Base) do
1398+
self.table_name = "comments"
1399+
alias_attribute :text, :body
1400+
end
1401+
1402+
subclass = Class.new(superclass) do
1403+
self.abstract_class = true
1404+
end
1405+
1406+
subsubclass = Class.new(subclass)
1407+
1408+
comment = subsubclass.build(body: "Text")
1409+
assert_equal "Text", comment.text
1410+
end
1411+
13961412
test "#alias_attribute with an association method issues a deprecation warning" do
13971413
message = <<~MESSAGE.gsub("\n", " ")
13981414
AttributeMethodsTest::ClassWithAssociationTarget model aliases `author`, but `author` is not an attribute. Starting in Rails 7.2, alias_attribute with non-attribute targets will raise. Use `alias_method :written_by, :author` or define the method manually.

0 commit comments

Comments
 (0)