1

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?

4

1 回答 1

0

I'm not 100% sure, but I think you would just add the line for embeds_many :circles to 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 :shapes relation 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.shapes available, but you can simply ignore these. Adding the embeds_many :circles will give you the methods for that relation, such as Browser.first.circles.

于 2012-10-05T08:23:18.627 回答