Created
November 3, 2010 05:01
-
-
Save rsofaer/660810 to your computer and use it in GitHub Desktop.
MongoMapper: Override by setting ID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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