2012-03-09 180 views
0

我有兩種模式。我試圖查詢一個模型有多少關係到另一個模型。我的型號如下: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 

我需要能夠查詢以下:沒有客戶

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

聯繫人與客戶

聯繫

Contact.where("clients.length > 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