Skip to content

Commit

Permalink
Fix #50499: instantiation of inherited classes when quering
Browse files Browse the repository at this point in the history
Previously, querying from the base class resulted in an object of the inherited type,
with 'ignored_columns' included in the 'attributes' method.

This behavior was inconsistent, as it did not occur when querying directly from the inherited class.
This fix ensures consistent behavior in class instantiation during queries.
  • Loading branch information
jvlara committed Jan 5, 2024
1 parent f481353 commit c8ad876
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions activerecord/lib/active_record/inheritance.rb
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,11 @@ def set_base_class # :nodoc:
end

private
def instantiate_instance_of(klass, attributes, column_types = {}, &block)
attributes.except!(*klass.ignored_columns) if using_single_table_inheritance?(attributes)
super
end

def inherited(subclass)
super
subclass.set_base_class
Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/cases/inheritance_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,7 @@ class Startup < Company
end

class Empire < Company
self.ignored_columns = [:description]
end

def test_inheritance_new_with_subclass_as_default
Expand All @@ -589,6 +590,13 @@ def test_inheritance_new_with_subclass_as_default
assert_equal "InheritanceAttributeTest::Empire", empire.type
assert_instance_of Empire, empire
end

def test_when_quering_from_base_class_instantiate_subclass_without_ignored_columns
empire = Empire.create!(name: "Empire")
empire_called_from_sti = Company.find(empire.id)
assert_not_includes(empire_called_from_sti.attributes.keys, "description")
assert_equal(empire_called_from_sti.attributes.keys.size, Empire.column_names.size)
end
end

class InheritanceAttributeMappingTest < ActiveRecord::TestCase
Expand Down

0 comments on commit c8ad876

Please sign in to comment.