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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.145.158