get record with at least one associated object

混江龙づ霸主 提交于 2020-01-11 11:37:33

问题


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)

回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/21263683/get-record-with-at-least-one-associated-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!