@@ -185,11 +185,34 @@ def fields_from_model_tags
185
185
186
186
def fields_from_model_associations
187
187
associations . each do |name , association |
188
- fields [ name ] = if association . is_a? ActiveRecord ::Reflection ::ThroughReflection
189
- field_from_through_association ( association )
190
- else
191
- ::Avo ::Mappings ::ASSOCIATIONS_MAPPING [ association . class ]
192
- end
188
+ fields [ name ] =
189
+ if association . polymorphic?
190
+ field_with_polymorphic_association ( association )
191
+ elsif association . is_a? ( ActiveRecord ::Reflection ::ThroughReflection )
192
+ field_from_through_association ( association )
193
+ else
194
+ ::Avo ::Mappings ::ASSOCIATIONS_MAPPING [ association . class ]
195
+ end
196
+ end
197
+ end
198
+
199
+ def field_with_polymorphic_association ( association )
200
+ Rails . application . eager_load! unless Rails . application . config . eager_load
201
+
202
+ types = polymorphic_association_types ( association )
203
+
204
+ {
205
+ field : "belongs_to" ,
206
+ options : {
207
+ polymorphic_as : ":#{ association . name } " ,
208
+ types : types . presence || "[] # Types weren't computed correctly. Please configure them."
209
+ }
210
+ }
211
+ end
212
+
213
+ def polymorphic_association_types ( association )
214
+ ActiveRecord ::Base . descendants . filter_map do |model |
215
+ Inspector . new ( model . name ) if model . reflect_on_all_associations ( :has_many ) . any? { |assoc | assoc . options [ :as ] == association . name }
193
216
end
194
217
end
195
218
@@ -293,5 +316,20 @@ def field(name, type)
293
316
end
294
317
end
295
318
end
319
+
320
+ # This class modifies the inspect function to correctly handle polymorphic associations.
321
+ # It is used in the polymorphic_association_types function.
322
+ # Without modification: Model(id: integer, name: string)
323
+ # After modification: Model
324
+ class Inspector
325
+ attr_accessor :name
326
+ def initialize ( name )
327
+ @name = name
328
+ end
329
+
330
+ def inspect
331
+ name
332
+ end
333
+ end
296
334
end
297
335
end
0 commit comments