Skip to content

Instantly share code, notes, and snippets.

@mrkurt
Created August 21, 2011 19:10
Show Gist options
  • Save mrkurt/1161008 to your computer and use it in GitHub Desktop.
Save mrkurt/1161008 to your computer and use it in GitHub Desktop.
The magical document eating has_many assignment
source :rubygems
gem 'mongoid'
mrkurt-2:mongoid-test kurt$ ./run.sh
Parent has 10 kids
There are now 0 kids
mrkurt-2:mongoid-test kurt$
require 'mongoid'
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("document_eater")
end
class Kid
include Mongoid::Document
belongs_to :parent
end
class Parent
include Mongoid::Document
has_many :kids
end
Kid.destroy_all
Parent.destroy_all
p = Parent.create!
10.times do |n|
k = Kid.create!
p.kids << k
end
p.reload
puts "Parent has #{p.kids.count} kids"
kids = Kid.all.to_a
p = Parent.find(p.id)
p.kids = kids
puts "There are now #{Kid.count} kids"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment