Reputation: 5148
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?
Upvotes: 0
Views: 473
Reputation: 1547
Given the following model:
class Client
include Mongoid::Document
belongs_to :contact
field :name, type: String
end
class Contact
include Mongoid::Document
has_many :clients
field :name, type: String
end
And the following insertions:
Contact.create(:name => "Bill")
jill = Contact.create(:name => "Jill")
jill.clients.create(:name => "Steve")
The following code will do what you need:
p "Has Clients"
Contact.any_in(_id: Client.all.distinct("contact_id")).each do |c|
p c
end
p "No Clients"
Contact.not_in(_id: Client.all.distinct("contact_id")).each do |c|
p c
end
Outputs:
"Has Clients"
#<Contact _id: 4f5b04b1e98c373917000002, _type: nil, name: "Jill">
"No Clients"
#<Contact _id: 4f5b04b1e98c373917000001, _type: nil, name: "Bill">
Full gist: https://gist.github.com/2010817
Upvotes: 2