- Mastering MongoDB 3.x
- Alex Giamas
- 158字
- 2021-08-20 10:10:52
Inheritance with Mongoid models
Here you can see an example of inheritance using Mongoid models:
class Canvas
include Mongoid::Document
field :name, type: String
embeds_many :shapes
end
class Shape
include Mongoid::Document
field :x, type: Integer
field :y, type: Integer
embedded_in :canvas
end
class Circle < Shape
field :radius, type: Float
end
class Rectangle < Shape
field :width, type: Float
field :height, type: Float
end
Now we have a Canvas class with many Shape objects embedded in it. Mongoid will automatically create a field, _type to distinguish between parent and child node fields. In scenarios where documents are inherited from their fields, relationships, validations, and scopes get copied down into their child documents, but not vice-versa.
embeds_many and embedded_in pair will create embedded subdocuments to store the relationships. If we want to store these via referencing to ObjectId we can do so by substituting these with has_many and belongs_to.
More examples on CRUD operations will follow in the next chapter.
推薦閱讀
- Mastering Hadoop 3
- Mastering Proxmox(Third Edition)
- 構(gòu)建高質(zhì)量的C#代碼
- 走入IBM小型機(jī)世界
- 網(wǎng)頁(yè)編程技術(shù)
- Windows XP中文版應(yīng)用基礎(chǔ)
- 返璞歸真:UNIX技術(shù)內(nèi)幕
- 樂高創(chuàng)意機(jī)器人教程(中級(jí) 下冊(cè) 10~16歲) (青少年iCAN+創(chuàng)新創(chuàng)意實(shí)踐指導(dǎo)叢書)
- 傳感器技術(shù)應(yīng)用
- WordPress Theme Development Beginner's Guide(Third Edition)
- 運(yùn)動(dòng)控制器與交流伺服系統(tǒng)的調(diào)試和應(yīng)用
- 具比例時(shí)滯遞歸神經(jīng)網(wǎng)絡(luò)的穩(wěn)定性及其仿真與應(yīng)用
- Prometheus監(jiān)控實(shí)戰(zhàn)
- The Python Workshop
- 云原生架構(gòu)進(jìn)階實(shí)戰(zhàn)