@@ -2,6 +2,10 @@ module PolymorphicIntegerType
2
2
3
3
module Extensions
4
4
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 )
5
9
6
10
def belongs_to ( name , scope = nil , **options )
7
11
options = scope if scope . kind_of? Hash
@@ -64,8 +68,10 @@ def remove_type_and_establish_mapping(name, options, scope)
64
68
condition = instance_exec ( &scope ) . merge ( condition ) if scope . is_a? ( Proc )
65
69
condition
66
70
}
71
+ return foreign_type , klass_mapping . to_i
67
72
else
68
73
options [ :scope ] ||= scope
74
+ return nil , nil
69
75
end
70
76
end
71
77
@@ -86,8 +92,10 @@ def has_many(name, scope = nil, **options, &extension)
86
92
scope = nil
87
93
end
88
94
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
91
99
end
92
100
93
101
def has_one ( name , scope = nil , **options )
@@ -96,8 +104,27 @@ def has_one(name, scope = nil, **options)
96
104
scope = nil
97
105
end
98
106
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
101
128
end
102
129
103
130
0 commit comments