@@ -2,6 +2,10 @@ module PolymorphicIntegerType
22
33 module Extensions
44 module ClassMethods
5+ ActiveRecord ::Reflection ::HasManyReflection . attr_accessor ( :foreign_integer_type )
6+ ActiveRecord ::Reflection ::HasManyReflection . attr_accessor ( :integer_type )
7+ ActiveRecord ::Reflection ::HasOneReflection . attr_accessor ( :foreign_integer_type )
8+ ActiveRecord ::Reflection ::HasOneReflection . attr_accessor ( :integer_type )
59
610 def belongs_to ( name , scope = nil , **options )
711 options = scope if scope . kind_of? Hash
@@ -64,8 +68,10 @@ def remove_type_and_establish_mapping(name, options, scope)
6468 condition = instance_exec ( &scope ) . merge ( condition ) if scope . is_a? ( Proc )
6569 condition
6670 }
71+ return foreign_type , klass_mapping . to_i
6772 else
6873 options [ :scope ] ||= scope
74+ return nil , nil
6975 end
7076 end
7177
@@ -86,8 +92,10 @@ def has_many(name, scope = nil, **options, &extension)
8692 scope = nil
8793 end
8894
89- remove_type_and_establish_mapping ( name , options , scope )
90- super ( name , options . delete ( :scope ) , **options , &extension )
95+ integer_type_values = remove_type_and_establish_mapping ( name , options , scope )
96+ super ( name , options . delete ( :scope ) , **options , &extension ) . tap do
97+ remove_integer_type_and_set_attributes_and_extension ( integer_type_values , reflections [ name . to_s ] )
98+ end
9199 end
92100
93101 def has_one ( name , scope = nil , **options )
@@ -96,8 +104,27 @@ def has_one(name, scope = nil, **options)
96104 scope = nil
97105 end
98106
99- remove_type_and_establish_mapping ( name , options , scope )
100- super ( name , options . delete ( :scope ) , **options )
107+ integer_type_values = remove_type_and_establish_mapping ( name , options , scope )
108+ super ( name , options . delete ( :scope ) , **options ) . tap do
109+ remove_integer_type_and_set_attributes_and_extension ( integer_type_values , reflections [ name . to_s ] )
110+ end
111+ end
112+
113+ def remove_integer_type_and_set_attributes_and_extension ( integer_type_values , reflection )
114+ foreign_integer_type = integer_type_values [ 0 ]
115+ integer_type = integer_type_values [ 1 ]
116+ is_polymorphic_integer = foreign_integer_type && integer_type
117+
118+ if is_polymorphic_integer
119+ reflection . foreign_integer_type = foreign_integer_type
120+ reflection . integer_type = integer_type
121+
122+ if Gem ::Version . new ( ActiveRecord ::VERSION ::STRING ) < Gem ::Version . new ( "6.1" )
123+ ActiveRecord ::Associations ::Association . prepend ( PolymorphicIntegerType ::PolymorphicForeignAssociationExtension )
124+ else
125+ ActiveRecord ::Associations ::ForeignAssociation . prepend ( PolymorphicIntegerType ::PolymorphicForeignAssociationExtension )
126+ end
127+ end
101128 end
102129
103130
0 commit comments