Skip to content

Instantly share code, notes, and snippets.

@rsofaer
Created November 3, 2010 05:01
Show Gist options
  • Select an option

  • Save rsofaer/660810 to your computer and use it in GitHub Desktop.

Select an option

Save rsofaer/660810 to your computer and use it in GitHub Desktop.
MongoMapper: Override by setting ID
require 'mongo_mapper'
MongoMapper.database = 'testing'
class SafeDoc
include MongoMapper::Document
key :name
safe
end
puts "With a 'safe' document class:"
first_document = SafeDoc.create(:name => 'Raphael')
puts "Created doc: #{first_document.to_mongo.inspect}."
second_document = SafeDoc.create(:id => first_document.id, :name => 'John')
puts "Created doc: #{second_document.to_mongo.inspect}."
puts "First document is now: #{first_document.reload.to_mongo.inspect}."
#puts first_document.reload.name == 'John'
#This outputs true
puts
puts "With attr_accessible on 'name':"
class ProtectedDoc
include MongoMapper::Document
key :name
safe
attr_accessible :name
end
first_document = ProtectedDoc.create(:name => 'Raphael')
puts "Created doc: #{first_document.to_mongo.inspect}."
second_document = ProtectedDoc.create(:id => first_document.id, :name => 'John')
puts "Created doc: #{second_document.to_mongo.inspect}."
puts "The create had no effect, but no error was raised, and second_document.persisted? is: #{second_document.persisted?}"
puts "First document is now: #{first_document.reload.to_mongo.inspect}."
#puts first_document.reload.name == 'John'
#This outputs false
#However:
puts "We have to use ProtectedDoc.new in order to expose this behavior."
third_document = ProtectedDoc.new(:name => 'John')
third_document.id = first_document.id
puts "With unsaved document: #{third_document.to_mongo.inspect}"
third_document.save
puts "After saving, the first document is: #{first_document.reload.to_mongo.inspect}."
#puts first_document.reload.name == 'John'
#This outputs true
#puts third_document.persisted?
#also true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment