I am using Rails 3 with Mongoid.
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.
Since you’re accessing referenced documents – your
usersmethod is a virtual attribute, which you can’t access during your query. You can however useuser_ids(the array ofUserids in yourFolderdocument) to perform the kinds of queries you want:Either of these should work for your personal scope:
And for your shared scope: