I am using mongoid in Rails 3 and I came across this problem:
Let’s say I have a Shape model:
class Shape
include Mongoid::Document
field :x, type: Integer
field :y, type: Integer
embedded_in :canvas
end
And a Canvas model (has many Shapes):
class Canvas
include Mongoid::Document
field :name, type: String
embeds_many :shapes
end
Then a Canvas model “has many Shapes”.
I have Browser model inherited from Canvas:
class Browser < Canvas
field :version, type: Integer
end
Then Browswer model should “has many Shapes” now.
But, now I have a “Circle” model inherited from Shape:
class Circle < Shape
field :radius, type: Float
end
And I want to let Browser model to “has many Circles” instead of “has many Shapes”. That is to say, I want to overwrite the “has many” relationship in Browser model from “has many Shapes” to “has many Circles”.
How should I do it?
I’m not 100% sure, but I think you would just add the line for
embeds_many :circlesto the Browser model. You wouldn’t need to remove the inherited relation.Since Circle inherits from Shape, circles will get stored in an array stored in the “shapes” key in the Browser document anyway, they’ll just have their _type attribute set to “Circle”. In other words, having the
embeds_many :shapesrelation doesn’t create anything in the DB that embedding many circles wouldn’t create anyway.It will, however, mean that you have methods such as
Browser.frist.shapesavailable, but you can simply ignore these. Adding theembeds_many :circleswill give you the methods for that relation, such asBrowser.first.circles.