[mongoid] validates_uniqueness_of not working for embedded / inherited documents?

246 views
Skip to first unread message

kshet26

unread,
May 12, 2010, 8:37:04 AM5/12/10
to Mongoid
Let's say I have a User model with a field of :username. If a person
signs up with an already used :username,
validates_uniqueness_of :username fails correctly and prevents the
record from being saved.

Now let's say I have a Friendship model (with a field
of :target_user_id) that is inherited from a Relationship model.
Friendships get embedded into User.

If a person tries to create multiple Friendships with the
same :target_user_id value, validates_uniqueness_of :target_user_id
DOES NOT fail. As a sanity check, I checked if
validates_length_of :target_user_id, :maximum => 2 would fail and it
does correctly.

Is this a bug or am I missing something in the way that Mongoid works?

kshet26

unread,
May 17, 2010, 1:38:08 PM5/17/10
to Mongoid
Anyone have any information on this? Is this intended or a possible
bug?

Durran Jordan

unread,
May 17, 2010, 1:50:34 PM5/17/10
to mon...@googlegroups.com
Probably need a little more thought around this, but right now it
would not work... I guess the best would be for mongoid's validator to
be smart enough to check if the field was unique for the same embedded
types across the database, or if a scope option was supplied then it
could be scoped to potentially just it's parent... I've seen some
forks already working on this type of solution.

kshet26

unread,
May 17, 2010, 2:26:53 PM5/17/10
to Mongoid
Would a validation be more efficient than me doing a query to see if a
matching record already exists?

Durran Jordan

unread,
May 17, 2010, 2:32:46 PM5/17/10
to mon...@googlegroups.com
You can do the query now as a workaround in a custom validator... The
validation once it would not be much different as far as efficiency
goes.

kshet26

unread,
May 17, 2010, 2:51:02 PM5/17/10
to Mongoid
That's what I thought, thanks so much!

tadatoshi

unread,
May 23, 2010, 3:48:18 PM5/23/10
to Mongoid
I've just found that validation on presence (I use
"validates :locale, :presence => true" like ActiveModel in Rails 3.0)
also doesn't fail on embedded document.
Strange thing is that it puts an error message correctly but the
document is still saved.
Reply all
Reply to author
Forward
0 new messages