Skip to content

Commit 880464a

Browse files
committed
DOCSP-42034-allow-custom-polymorphic-types
1 parent 884292f commit 880464a

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

source/reference/associations.txt

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1211,6 +1211,44 @@ that a bundle may contain other bundles or products:
12111211
has_many :items, polymorphic: true
12121212
end
12131213

1214+
Starting in version 9.0.2, Mongoid allows you to store an arbitrary string in the
1215+
`*_type` attribute. This feature allows the class resolution to be handled at
1216+
runtime.
1217+
1218+
For example:
1219+
1220+
.. code-block:: ruby
1221+
1222+
class Item
1223+
include Mongoid::Document
1224+
belongs_to :unitable, polymorphic: true, type_field_method:
1225+
:resolve_unitable_type
1226+
field :unitable_type, type: String
1227+
1228+
def resolve_unitable_type(value)
1229+
case value
1230+
when "warehouse"
1231+
Unit
1232+
when "store"
1233+
Store
1234+
else
1235+
nil
1236+
end
1237+
end
1238+
end
1239+
1240+
unit = Unit.create(name: "Warehouse")
1241+
item = Item.create(unitable_id: unit.id, unitable_type: "warehouse")
1242+
1243+
store = Store.create(name: "Downtown")
1244+
store_item = Item.create(unitable_id: store.id, unitable_type: "store")
1245+
1246+
# Results in
1247+
# { "_id": ObjectId("..."), "unitable_id": ObjectId("..."), "unitable_type": "warehouse" }
1248+
# { "_id": ObjectId("..."), "unitable_id": ObjectId("..."), "unitable_type": "store" }
1249+
1250+
1251+
12141252
``has_and_belongs_to_many`` associations do not support polymorphism.
12151253

12161254

0 commit comments

Comments
 (0)