Created
March 22, 2012 10:57
-
-
Save matthiassiegel/2157677 to your computer and use it in GitHub Desktop.
MongoMapper modified safe example
This file contains 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
$LOAD_PATH.unshift(File.expand_path('../../lib', __FILE__)) | |
require 'mongo_mapper' | |
MongoMapper.database = 'testing' | |
class User | |
include MongoMapper::Document | |
key :_id, String, :default => 'abcde' | |
key :email, String | |
key :number, Integer | |
end | |
# Drop collection and ensure unique index on email | |
User.collection.drop | |
User.ensure_index(:_id, :unique => true) | |
User.ensure_index(:email, :unique => true) | |
User.create(:email => 'nunemaker@gmail.com', :number => 1) | |
puts User.all.inspect | |
User.create(:email => 'nunemaker@gmail.com', :number => 2) | |
puts User.all.inspect | |
# save method also takes options, including :safe | |
# which will force raise when duplicate is hit | |
begin | |
user = User.new(:email => 'nunemaker@gmail.com', :number => 3) | |
user.save(:safe => true) | |
rescue Mongo::OperationFailure => e | |
puts 'Mongo Operation failure raised because duplicate email was entered' | |
puts e.inspect | |
puts | |
end | |
puts User.all.inspect | |
# Mark user model as safe, same as doing this... | |
# class User | |
# include MongoMapper::Document | |
# safe | |
# end | |
User.safe | |
begin | |
User.create(:email => 'nunemaker@gmail.com', :number => 4) | |
rescue Mongo::OperationFailure => e | |
puts 'Mongo Operation failure raised because duplicate email was entered' | |
puts e.inspect | |
end | |
puts User.all.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment