get record with at least one associated object

2020-04-20 23:50发布

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)

2条回答
ら.Afraid
2楼-- · 2020-04-21 00:32

You can do

User.where(:tasks.exists => true).limit(10)

Update:

Worked for me when doing:

u = User.new
t = u.tasks.build
t.save
u.save

u = User.new
u.save

User.where(:tasks.exists => true).limit(10).count
=> 1
查看更多
家丑人穷心不美
3楼-- · 2020-04-21 00:37

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, the belongs_to :user in your Task will add a :user_id field to the tasks collection. That leaves you with horrific things like this:

user_ids = Task.all.distinct(:user_id)
users    = User.where(:id => user_ids).limit(10)

Of course, if you had embeds_many :tasks instead of has_many :tasks then you could query the :tasks inside the users 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:

User.where(:num_tasks.gt => 0).limit(10)
查看更多
登录 后发表回答