Polymorphic References Association

279 views
Skip to first unread message

Avand

unread,
Mar 4, 2011, 11:46:52 AM3/4/11
to Mongoid
Hello,

I'm trying to create a polymorphic references association with
Mongoid. I'm using 2.0.0.beta.20, though it doesn't seem to be
supported in 2.0.0.rc.7 either (?).

Here's what I want to achieve:

class Car
include Mongoid::Document
end

class House
include Mongoid::Document
end

class Person
include Mongoid::Document
references_one :asset
end

@person_with_house.asset.is_a?(House) # => true
@person_with_car.asset.is_a?(Car) # => true

In ActiveRecord, I would specify that the belongs_to relationship is
polymorphic and AR would expect two attributes: asset_type and
asset_id.

Does this model make sense using Mongo? Is there a better way to model
this? Does Mongoid support this type of polymorphism?

Thanks in advance, Avand

Durran Jordan

unread,
Mar 4, 2011, 12:06:31 PM3/4/11
to mon...@googlegroups.com
In rc.7, same as AR:


class Car
  include Mongoid::Document
  has_one :person, :as => :asset

end

class House
  include Mongoid::Document
  has_one :person, :as => :asset

end

class Person
  include Mongoid::Document
  belongs_to :asset, :polymorphic => true
end

2011/3/4 Avand <av...@avandamiri.com>

Avand

unread,
Mar 14, 2011, 11:22:35 AM3/14/11
to Mongoid
Awesome.

What about for embedded relationships? If I wanted Person to embed Car
or House as "asset"?

Durran Jordan

unread,
Mar 23, 2011, 12:15:14 PM3/23/11
to mon...@googlegroups.com
You would use the same syntax for embedded relationships as well, just with:

embeds_one :person, :as => :asset

and

embedded_in :asset, :polymorphic => true

2011/3/14 Avand <av...@avandamiri.com>
Reply all
Reply to author
Forward
0 new messages