@@ -1211,6 +1211,53 @@ that a bundle may contain other bundles or products:
1211
1211
has_many :items, polymorphic: true
1212
1212
end
1213
1213
1214
+ Starting in version 9.0.2, Mongoid adds support for custom polymorphic types through
1215
+ a global registry. You can specify alternative keys to represent different
1216
+ classes, thus decoupling the code from the data. The following example specifies
1217
+ the string ``"dept"`` as an alternate key for the ``Department`` class:
1218
+
1219
+ .. code-block:: ruby
1220
+
1221
+ class Department
1222
+ include Mongoid::Document
1223
+ identify_as 'dept'
1224
+ has_many :managers, as: :unit
1225
+ end
1226
+
1227
+ In the preceding example, the ``identify_as 'dept'`` directive instructs Mongoid
1228
+ to store this class in the database as the string ``"dept"``. You can also specify
1229
+ multiple aliases. For example, you can specify the option as:
1230
+ ``identify_as 'dept', 'div', 'agency'``, in which case the first key is the "default",
1231
+ and the others are used only for looking up records. This lets you refactor your
1232
+ code without breaking the associations in your data.
1233
+
1234
+ Polymorphic type aliases are global. The keys you specify must be unique across your
1235
+ entire code base. However, it is possible to register alternative resolvers, which
1236
+ may be used for different subsets of your models. In this case, the keys must
1237
+ only be unique for each resolver. The following example shows how to register
1238
+ alternate resolvers:
1239
+
1240
+ .. code-block:: ruby
1241
+
1242
+ Mongoid::ModelResolver.register_resolver Mongoid::ModelResolver.new, :eng
1243
+ Mongoid::ModelResolver.register_resolver Mongoid::ModelResolver.new, :purch
1244
+
1245
+ module Engineering
1246
+ class Department
1247
+ include Mongoid::Document
1248
+ identify_as 'dept', resolver: :eng
1249
+ end
1250
+
1251
+ module Purchasing
1252
+ class Department
1253
+ include Mongoid::Document
1254
+ identify_as 'dept', resolver: :purch
1255
+ end
1256
+
1257
+
1258
+ Both ``Engineering::Department`` and ``Purchasing::Department`` are aliased as
1259
+ ``"dept"``, but use their own resolver to avoid conflicts.
1260
+
1214
1261
``has_and_belongs_to_many`` associations do not support polymorphism.
1215
1262
1216
1263
0 commit comments