Mongoid查询关系数量

时间:2012-03-09 17:12:44

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid

我有两个型号。我试图查询模型与其他模型有多少关系。我的模型如下:

# 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

我需要能够查询以下内容:

与NO客户联系

Contact.where("clients.length == 0")

与客户联系

Contact.where("clients.length > 0")

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

鉴于以下模型:

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

以下插入内容:

Contact.create(:name => "Bill")
jill = Contact.create(:name => "Jill")
jill.clients.create(:name => "Steve")

以下代码将满足您的需求:

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

输出:

"Has Clients"
#<Contact _id: 4f5b04b1e98c373917000002, _type: nil, name: "Jill">
"No Clients"
#<Contact _id: 4f5b04b1e98c373917000001, _type: nil, name: "Bill">

全部要点: https://gist.github.com/2010817