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 #
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With