defself.polymorphic_class_for(name) "Test::#{name}".constantize end end end
Test::A Load (2.0ms) SELECT `as`.* FROM `as` WHERE `as`.`id` = 1 LIMIT 1
至於為什麼是這樣改呢?
去翻了一下 source code,發現其他的關聯的 klass 都是指定自己,只有 polymorphic 的關聯的 klass 是會變動的,用繼承的關係去蓋掉 parent 的 method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 其他關聯 defklass reflection.klass end
# 多型關聯 moduleActiveRecord moduleAssociations # = Active Record Belongs To Polymorphic Association classBelongsToPolymorphicAssociation < BelongsToAssociation #:nodoc: defklass type = owner[reflection.foreign_type] type.presence && owner.class.polymorphic_class_for(type) end # ...
另外前面有提到 ActiveRecord6 以前還沒有這個方式可以修改
1 2 3 4 5 6 7 8 9 10
# version 6.1 defklass type = owner[reflection.foreign_type] type.presence && owner.class.polymorphic_class_for(type) end # version 5.2.3 defklass type = owner[reflection.foreign_type] type.presence && type.constantize end
# Returns the value to be stored in the polymorphic type column for Polymorphic Associations. defpolymorphic_name store_full_class_name ? base_class.name : base_class.name.demodulize end
# Returns the class for the provided +name+. # # It is used to find the class correspondent to the value stored in the polymorphic type column. defpolymorphic_class_for(name) if store_full_class_name name.constantize else compute_type(name) end end
其實跟前面的做法很像,只是要改的方向不同而已
以上面的例子來說,現在我的需求變成在資料庫的 target_type 要存的資料從 A / B 變成 a / b