This is a note for myself for a project I am actually working on that I thought could be useful to share :)
More info here.
CYCLIC RELATIONS on MONGODB WITH MONGOID
A document can recursively embed itself using recursively_embeds_many, which provides accessors for the parent and children.
class Tag
include Mongoid::Document
recursively_embeds_many
field :name
end
programming = Tag.new(:name => 'programming')
ruby = programming.child_tags.build(:name => 'ruby')
python = programming.child_tags.build(:name => 'python')
programming.child_tags
ruby.parent_tag
python.parent_tag
Mongoid has added a tag which automatically makes callbacks for embedded child objects when the parent object is saved.
You can find it at the end of the mongoid documentation on embedding.
class Post
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
embeds_many :comments, cascade_callbacks: true
accepts_nested_attributes_for :comments
end
Ever wondered how to create nested hash in ruby?
Here it is:
1.9.3p125 :001 > a = Hash.new{|h,k| h[k]=Hash.new(&h.default_proc) }
=> {}
1.9.3p125 :002 > a[2][1] = 2
=> 2
1.9.3p125 :003 > a[2][2][3] = 2
=> 2
1.9.3p125 :004 > a[2][2][4] = 5
=> 5
1.9.3p125 :005 > a[3][1][1][1] = 7
=> 7
1.9.3p125 :006 > a
=> {2=>{1=>2, 2=>{3=>2, 4=>5}}, 3=>{1=>{1=>{1=>7}}}}
:) sweet!
If:
script/rails generate controller Hello
Is failing, try to remember that you have probably installed more than one version of rails in your history, so you might need to call:
rvm use 1.9.1 —default :)