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

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.

主站蜘蛛池模板: 闻喜县| 富顺县| 淮北市| 尉氏县| 陆川县| 虎林市| 钦州市| 鸡东县| 秭归县| 华亭县| 昆明市| 灌云县| 汉源县| 山东| 肥东县| 陇南市| 株洲县| 洞头县| 富源县| 阿瓦提县| 泸水县| 昔阳县| 滦南县| 晋中市| 嘉黎县| 和平县| 奉节县| 玛沁县| 威宁| 兴化市| 利辛县| 东平县| 页游| 盐源县| 赣州市| 独山县| 安陆市| 扶余县| 通辽市| 弥勒县| 瓦房店市|