我正在尝试使用Mongoid3将多态添加到我的嵌入关系中。
我有一个Item必须包含我的信息的embed_one对象的类。该协议是:
-我对象的类型可以是其中之一:Calendar,Sticker,Picture,
-无论对象的类型如何,我都想通过唯一的“键”来访问它:详细信息,
例如:
pry> my_item1.detail
=> `<Picture _id: 1234>`
pry> my_item2.detail
=> `<Sticker _id: 8964>`
pry>
Run Code Online (Sandbox Code Playgroud)
首先,我尝试使用关键字as和此处描述的多态:https : //github.com/mongoid/mongoid/issues/902
例如:
class Item
include Mongoid::Document
embeds_one :detail, as: :item_slot
end
class Picture
include Mongoid::Document
embedded_in :item_slot, polymorphic: true
end
class Calendar
include Mongoid::Document
embedded_in :item_slot, polymorphic: true
end
class Sticker
include Mongoid::Document
embedded_in :item_slot, polymorphic: true
end
Run Code Online (Sandbox Code Playgroud)
然后,我尝试访问我的详细信息,但不幸的是,我收到此消息错误:
pry(main)> i = …Run Code Online (Sandbox Code Playgroud)