Can rails scopes filter on the number of associated classes for a given field

故事扮演 提交于 2019-12-06 07:50:49

Since you're accessing referenced documents - your users method is a virtual attribute, which you can't access during your query. You can however use user_ids (the array of User ids in your Folder document) to perform the kinds of queries you want:

Either of these should work for your personal scope:

scope :personal, where(:user_ids.size => 0)
# or
scope :personal, where(:user_ids => [])

And for your shared scope:

scope :shared, where(:user_ids.ne => [])
scope :personal, where({ "$or" => [{:user_ids => nil}, {:user_ids => {"$size"=>0}}] })
scope :shared, where({ "$nor" => [{:user_ids => nil}, {:user_ids => {"$size"=>0}}] })

This should handle both the cases when :user_ids is not set or is null and when it is set to an empty array.

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