@@ -58,6 +58,8 @@ def remove_type_and_establish_mapping(name, options, scope)
58
58
59
59
options [ :foreign_key ] ||= "#{ poly_type } _id"
60
60
foreign_type = options . delete ( :foreign_type ) || "#{ poly_type } _type"
61
+ options [ :foreign_integer_type ] = foreign_type
62
+ options [ :integer_type ] = klass_mapping . to_i
61
63
62
64
options [ :scope ] ||= -> {
63
65
condition = where ( foreign_type => klass_mapping . to_i )
@@ -87,7 +89,9 @@ def has_many(name, scope = nil, **options, &extension)
87
89
end
88
90
89
91
remove_type_and_establish_mapping ( name , options , scope )
90
- super ( name , options . delete ( :scope ) , **options , &extension )
92
+ super ( name , options . delete ( :scope ) , **options . except ( :foreign_integer_type , :integer_type ) , &extension ) . tap do |_ |
93
+ remove_integer_type_and_set_attributes_and_extension ( options , ActiveRecord ::Reflection ::HasManyReflection , reflections [ name . to_s ] )
94
+ end
91
95
end
92
96
93
97
def has_one ( name , scope = nil , **options )
@@ -97,7 +101,28 @@ def has_one(name, scope = nil, **options)
97
101
end
98
102
99
103
remove_type_and_establish_mapping ( name , options , scope )
100
- super ( name , options . delete ( :scope ) , **options )
104
+ super ( name , options . delete ( :scope ) , **options . except ( :foreign_integer_type , :integer_type ) ) . tap do |_ |
105
+ remove_integer_type_and_set_attributes_and_extension ( options , ActiveRecord ::Reflection ::HasOneReflection , reflections [ name . to_s ] )
106
+ end
107
+ end
108
+
109
+ def remove_integer_type_and_set_attributes_and_extension ( options , klass , reflection )
110
+ foreign_integer_type = options . delete :foreign_integer_type
111
+ integer_type = options . delete :integer_type
112
+ is_polymorphic_integer = foreign_integer_type && integer_type
113
+
114
+ if is_polymorphic_integer
115
+ klass . attr_accessor ( :foreign_integer_type )
116
+ klass . attr_accessor ( :integer_type )
117
+ reflection . foreign_integer_type = foreign_integer_type
118
+ reflection . integer_type = integer_type
119
+
120
+ if Gem ::Version . new ( ActiveRecord ::VERSION ::STRING ) < Gem ::Version . new ( "6.1" )
121
+ ActiveRecord ::Associations ::Association . prepend ( ActiveRecord ::Associations ::PolymorphicForeignAssociationExtension )
122
+ else
123
+ ActiveRecord ::Associations ::ForeignAssociation . prepend ( ActiveRecord ::Associations ::PolymorphicForeignAssociationExtension )
124
+ end
125
+ end
101
126
end
102
127
103
128
0 commit comments