官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 志丹县| 永兴县| 曲水县| 温泉县| 泽州县| 宣化县| 浦东新区| 巨野县| 新干县| 商城县| 罗源县| 集贤县| 寿阳县| 板桥市| 西贡区| 延庆县| 湘潭县| 遵义市| 桂阳县| 乡宁县| 永宁县| 东宁县| 平南县| 徐州市| 大英县| 兴隆县| 鱼台县| 敖汉旗| 锦州市| 靖远县| 安远县| 泽库县| 安陆市| 景泰县| 林芝县| 平谷区| 红桥区| 库尔勒市| 磴口县| 静海县| 温泉县|