Rails范围筛选器可以根据给定字段的关联类数进行过滤 [英] Can rails scopes filter on the number of associated classes for a given field

查看:55
本文介绍了Rails范围筛选器可以根据给定字段的关联类数进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Rails 3与Mongoid一起使用.

I am using Rails 3 with Mongoid.

我有一个Folder类,然后可以与其他User类共享

I have a Folder class that can then be shared with other User classes as such

class Folder
  has_one :owner
  has_many :users

我正在尝试创建两个作用域,一个作用域可用于返回所有私有文件夹,另一个作用域可返回所有共享文件夹.有什么方法可以计算范围内的关联数目?

I am trying to create two scopes one that can be used to return all private folders, and one to return all shared folders. Is there any way to count the number of associations within a scope?

  scope :personal, where(:users.count => 0)    #Erroring on count...
  scope :shared, where(:users.count.gt => 0)  #Erroring on count...

我已经考虑过构建方法,但是我希望将范围与我希望将它们与其他范围链接在一起.

I've considered building methods instead but would prefer scopes as I wish to chain them with other scopes.

推荐答案

由于您正在访问引用的文档-您的users方法是一个虚拟属性,在查询期间无法访问.但是,您可以使用user_ids(在Folder文档中的User id的数组)执行所需的查询类型:

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 => [])

对于您的共享范围:

scope :shared, where(:user_ids.ne => [])

这篇关于Rails范围筛选器可以根据给定字段的关联类数进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆