I have two models. I am trying to query a model for how many relationships it has to the other model. My models are as follows:
# app/models/client.rb
class Client
include Mongoid::Document
belongs_to :contact
...
end
# app/models/contact.rb
class Contact
include Mongoid::Document
has_many :clients
...
end
I need to be able to query for the following:
Contacts with NO clients
Contact.where("clients.length == 0")
Contacts with Clients
Contact.where("clients.length > 0")
Can anyone help me with how I would do about this?
Given the following model:
And the following insertions:
The following code will do what you need:
Outputs:
Full gist:
https://gist.github.com/2010817