Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix instantiation of inherited classes when querying #50553

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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