Skip to content

Instantly share code, notes, and snippets.

@durran
Created August 6, 2010 00:11
Show Gist options
  • Save durran/510616 to your computer and use it in GitHub Desktop.
Save durran/510616 to your computer and use it in GitHub Desktop.
require 'rubygems'
puts ENV["GEM_HOME"]
require 'mongoid'
require 'mongoid/version'
puts "Using Mongoid: #{Mongoid::VERSION}"
Mongoid.master = Mongo::Connection.new.db("mongoid_playground")
class Orphan
include Mongoid::Document
attr_accessor :mode
field :name, :type => String
embedded_in :parent, :inverse_of => :orphans
def loud_speak
puts "HOLLLLLLLA! #{self.name}"
end
def soft_speak
puts "holla. #{self.name}"
end
def speak
puts "mode = #{self.mode}" #mode doesn't exist
#eval "#{@mode}_speak"
soft_speak
end
end
class Parent
include Mongoid::Document
cache
field :name, :type => String
embeds_many :orphans
end
class Child < Parent
end
Parent.delete_all
Child.delete_all
p = Parent.new(:title => "parent1")
o = Orphan.new(:name => "Annie")
p.orphans << o
p.save
results = Parent.all
results.each{ |r| r.orphans.first.mode = "loud" }
results.each{ |r| r.orphans.first.speak }
@durran
Copy link
Author

durran commented Aug 6, 2010

I added cache to parent on line 37 to show you how to resolve it... attr_accessor works fine - you were doing a second iteration over the result set which was hitting the database again (unlike active record which brings everything into memory). Mongoid uses a cursor so if you didnt want to do that on iteration 2 you cache the class in this case.

See the caching section: http://mongoid.org/docs/extras/

If you had printed out "mode" in the first iteration you would have seen it get set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment