您链接到的示例有点误导(或者很难理解),因为它没有显示
Item
模型为了在模型中使用继承,您需要定义一个键
_type
在父模型上。然后,MongoMapper将自动将该键设置为该文档的实际类的类名。例如,您的模型现在看起来如下所示:
class Item
include MongoMapper::Document
key :name, String
key :_type, String
end
class Picture < Item
key :url, String
end
class Video < Item
key :length, Integer
end
以及搜索的输出(假设您创建了
Picture
对象)将变成:
>> Item.all
=> [#<Picture name: "Testing", _type: "Picture", created_at: Sun, 03 Jan 2010 20:02:48 PST -08:00, updated_at: Mon, 04 Jan 2010 13:01:31 PST -08:00, _id: 4b416868010e2a04d0000002, views: 0, user_id: 4b416844010e2a04d0000001, description: "lorem?">]
>> Video.all
=> []
>> Picture.all
=> [#<Picture name: "Testing", _type: "Picture", created_at: Sun, 03 Jan 2010 20:02:48 PST -08:00, updated_at: Mon, 04 Jan 2010 13:01:31 PST -08:00, _id: 4b416868010e2a04d0000002, views: 0, user_id: 4b416844010e2a04d0000001, description: "lorem?">]