Skip to content

Instantly share code, notes, and snippets.

@jnunemaker
Created December 23, 2009 13:52
Show Gist options
  • Save jnunemaker/262534 to your computer and use it in GitHub Desktop.
Save jnunemaker/262534 to your computer and use it in GitHub Desktop.
How to validate uniqueness of embedded objects
require 'pp'
require 'rubygems'
require 'mongo_mapper'
MongoMapper.database = 'testing'
class Rating
include MongoMapper::EmbeddedDocument
key :user_id, ObjectId
key :score, Integer
validate :uniqueness_of_user_id
def widget
_root_document
end
private
def uniqueness_of_user_id
if widget.ratings.select { |r| r.user_id == user_id }.size > 1
errors.add(:user_id, 'has already rated this widget')
end
end
end
class Widget
include MongoMapper::Document
key :name, String
key :user_id, ObjectId
many :ratings
validates_associated :ratings
end
Widget.collection.remove # clear collection before each run
rating = Rating.new(:user_id => Mongo::ObjectID.new)
widget = Widget.new(:ratings => [rating, rating.clone])
puts widget.valid? # false
widget2 = Widget.new(:ratings => [rating, Rating.new(:user_id => Mongo::ObjectID.new)])
puts widget2.valid? # true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment