2012-07-04 68 views
1

我有以下結構:查詢嵌入文檔匹配多個屬性

class User 
    include Mongoid::Document 
end 

class Resource 
    include Mongoid::Document 
    embeds_many :permissions 
end 

class Permission 
    include Mongoid::Document 
    embedded_in :resource 

    field :read, type: Boolean 
    field :write, type: Boolean 

    field :user_id, type: BSON::ObjectId 
end 

現在讓我們假設我有以下數據:

1.9.3p194 :001 > a = User.create 
=> #<User _id: 4ff46818f83222daf9000001, _type: nil> 
1.9.3p194 :002 > b = User.create 
=> #<User _id: 4ff4681bf83222daf9000002, _type: nil> 
1.9.3p194 :003 > r = Resource.create 
=> #<Resource _id: 4ff46822f83222daf9000003, _type: nil> 
1.9.3p194 :004 > r.permissions.create(read: true, user_id: a.id) 
=> #<Permission _id: 4ff46835f83222daf9000004, _type: nil, read: true, write: nil, user_id: 4ff46818f83222daf9000001> 
1.9.3p194 :005 > r.permissions.create(read: true, write: true, user_id: b.id) 
=> #<Permission _id: 4ff4684af83222daf9000005, _type: nil, read: true, write: true, user_id: 4ff4681bf83222daf9000002> 

現在我想找到用戶A擁有所有資源寫訪問(應該是none)

1.9.3p194 :007 > Resource.where('permissions.write' => true).where('permissions.user_id' => a.id).all.entries 
=> [#<Resource _id: 4ff46822f83222daf9000003, _type: nil>] 

這顯然失敗了,因爲對於每個where子句有匹配。 這將是什麼正確的解決方案?有沒有辦法爲嵌入式文檔查詢做and

回答

1

試試這個

Resource.where(:permissions.matches => {:write => true, :user_id => a.id}).all 
+0

這似乎是正確的mongoid2。因爲我使用的是mongoid3(應該提到)解決方案是:'Resource.where(:permissions.elem_match => {:write => true,:user_id => a.id})' – mxhaack

-1

試試這個:

Resource.Permission.where(寫:真,USER_ID:a.id)

+0

將返回:'NoMethodError:未定義的方法'權限'資源:類' – mxhaack