I have the following schema in mongoid:
User has many tasks - has_many :tasks
Task belongs to user - belongs_to :user
How can I get only 10 first users with at least one task?
Something like this:
User.where(:tasks.ne => [] ).limit(10)
I have the following schema in mongoid:
User has many tasks - has_many :tasks
Task belongs to user - belongs_to :user
How can I get only 10 first users with at least one task?
Something like this:
User.where(:tasks.ne => [] ).limit(10)
You can do
Update:
Worked for me when doing:
Your problem is that Mongoid's
has_many
doesn't leave anything in the parent document so there are no queries on the parent document that will do anything useful for you. However, thebelongs_to :user
in yourTask
will add a:user_id
field to thetasks
collection. That leaves you with horrific things like this:Of course, if you had
embeds_many :tasks
instead ofhas_many :tasks
then you could query the:tasks
inside theusers
collection as you want to. OTOH, this would probably break other things.If you need to keep the tasks separate (i.e. not embedded) then you could set up a counter in
User
to keep track of the number of tasks and then you could say things like: