Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB mongoid self reference relationship

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 #

like image 914
Alex Avatar asked Jun 30 '11 13:06

Alex


1 Answers

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.

like image 156
rubish Avatar answered Sep 19 '22 05:09

rubish