Reputation: 6475
I am new to mongo/mongoid and I am trying to setup a self referencing relationships on my sites table.
# sites model
has_many :child_sites, :class_name => 'Site'
belongs_to :parent, :class_name => 'Site'
#controller
@event = current_site.child_sites.build(params[:site])
current_site is a function that returns the current site object.
I get this error -
undefined method `entries' for #
Upvotes: 7
Views: 6044
Reputation: 10907
You can try changing your relation definitions to the following:
has_many :child_sites, :class_name => 'Site', :cyclic => true
belongs_to :parent_site, :class_name => 'Site', :cyclic => true
I don't know exactly what it does, but I remember it being discussed in the Mongoid google group. If that doesn't work, you should try to set inverse_of
on both the relation macros. Most of the time setting inverse_of
correctly does the job.
has_many :child_sites, :class_name => 'Site', :inverse_of => :parent_site
belongs_to :parent_site, :class_name => 'Site', :inverse_of => :child_sites
About the extra queries, yes there would be extra queries whenever you want to fetch child_sites of a site or the parent site of a site.
You should consider embedding child sites in parent site, but keep in mind that way you would loose the ability to query child sites in a stand_alone manner. You would always have to access any child site as "parent_site > child_sites".
Also keep in mind the 16MB limit on size of document, which is hard to reach, but might be possible if there are a lot of child sites for a parent and if you are storing template info, like html, css etc. in the document itself.
Upvotes: 14
Reputation: 4810
Cyclic was originally implemented for embedded documents (see user group entry). To make this working on mongoid 2.3 or higher you have to remove the cyclic option:
has_many :child_sites, :class_name => 'Site'
belongs_to :parent_site, :class_name => 'Site'
Upvotes: 4
Reputation: 2857
Can't you use recursively_embeds_many
or recursively_embeds_one
? http://mongoid.org/en/mongoid/docs/relations.html#common
Upvotes: 2