mongoid query - calling the size method produces an error


When I execute this query:

User.where(:comments.size => 10)

I am getting the following error:

undefined method `size' for :comments:Symbol

But according to the documentation here:

This should be possible. So, why the error?

Note: 'comments' is separate collection from User with a 'has_and_belongs_to_many' relationship.

I am using mongoid 3.0.0 and bson_ext 1.6.1

Thanks in advance!

By : charleetm

This will work if User embeds Comments but not when you relate User to Comments. It works for embedding because of the $size operator (although, this is not a super efficient query to perform. Better to cache the size in a separate field).

Use with_size, not size, with Mongoid 3. It will translate to the MongoDB $size operator.

Queryable#with_size: Add $size selection. Matches documents who's array field has the exact size of the provided value. This is named with_size not to conflict with Ruby's Enumerable#size or Symbol#size." (from the Origin Selection documentation)

This video can help you solving your question :)
By: admin