Skip to content

Instantly share code, notes, and snippets.

@kouky
Created May 13, 2010 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kouky/399814 to your computer and use it in GitHub Desktop.
Save kouky/399814 to your computer and use it in GitHub Desktop.
gem "mongo", "1.0"
gem "bson_ext", "1.0"
gem "mongo_ext", "0.19.3"
gem "mongo_mapper", "0.7.5"
require 'mongo_mapper'
MongoMapper.database = 'shopping'
class List
include MongoMapper::Document
key :name, String
many :items
def destroy_item!(item_id)
items.delete_if do |i|
i.id == item_id
end
save
end
end
class Item
include MongoMapper::EmbeddedDocument
key :price, Float
end
# Setup prop
list = List.new({:name => 'groceries'})
cheap_item = Item.new({:price => 5.00})
expensive_item = Item.new({:price => 3.00})
list.items = [] << cheap_item << expensive_item
list.save
puts "Is item count 2: #{list.items.count == 2}"
# Deletion by object id directly works fine
list.destroy_item!(expensive_item.id)
puts "Is item count 1: #{list.items.count == 1}"
# However if we send the object id as a string we get into trouble
list.destroy_item!(cheap_item.id.to_s)
puts "Is item count 0: #{list.items.count == 0}"
# This matters a fair bit when you are using restful resources over the web
# to handle the removal and updating of persisted objects.
#
# For example using sinatra we can handle a post to the
# resource /items/:list_id/:item_id/delete
#
# Rack then makes :item_id available in our params hash as a string,
# and from there you can get easily caught out as in the example above.
#
# I don't mind working around this with my model code - it might not even be a bug
# in mongo mapper bug perse. Just a bit assyemtric considering we can successfully
# query for an object with find with the id represented as a string. The same
# should apply to equivalence tests on object ids.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment