Skip to content

Commit e56a094

Browse files
committed
Fix usage of self.inherited
This commit fixes issue rails#50003 where using `super` after adding relations to the subclass or defining filter attributes in the subclass in the method `self.inherited` lead to warnings and removed previously defined filter_attributes
1 parent 16607e3 commit e56a094

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

activerecord/lib/active_record/core.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -384,8 +384,8 @@ def inherited(subclass)
384384
@arel_table = nil
385385
@predicate_builder = nil
386386
@inspection_filter = nil
387-
@filter_attributes = nil
388-
@generated_association_methods = nil
387+
@filter_attributes ||= nil
388+
@generated_association_methods ||= nil
389389
end
390390
end
391391

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# frozen_string_literal: true
2+
3+
require "cases/helper"
4+
5+
module Inherited
6+
# When running the test with `RAILS_STRICT_WARNINGS` enabled, the `belongs_to`
7+
# call should not emit a warning that the constant `GeneratedAssociationMethods`
8+
# is already defined.
9+
class Person < ActiveRecord::Base; end
10+
11+
class Device < ActiveRecord::Base
12+
def self.inherited(subclass)
13+
subclass.belongs_to :person, inverse_of: subclass.name.demodulize.tableize.to_sym
14+
subclass.filter_attributes = [:secret_attribute, :"#{subclass.name.demodulize.downcase}_key"]
15+
super
16+
end
17+
end
18+
19+
class Computer < Device; end
20+
21+
class Vehicle < ActiveRecord::Base
22+
def self.inherited(subclass)
23+
super
24+
subclass.belongs_to :person, inverse_of: subclass.name.demodulize.tableize.to_sym
25+
subclass.filter_attributes = [:secret_attribute, :"#{subclass.name.demodulize.downcase}_key"]
26+
end
27+
end
28+
29+
class Car < Vehicle; end
30+
end
31+
32+
class InheritedTest < ActiveRecord::TestCase
33+
def test_super_before_filter_attributes
34+
assert_equal %i[secret_attribute car_key], Inherited::Car.filter_attributes
35+
end
36+
37+
def test_super_after_filter_attributes
38+
assert_equal %i[secret_attribute computer_key], Inherited::Computer.filter_attributes
39+
end
40+
end

0 commit comments

Comments
 (0)