我有以下结构:
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 具有写入权限的所有资源(应该没有)
1.9.3p194 :007 > Resource.where('permissions.write' => true).where('permissions.user_id' => a.id).all.entries
=> [#<Resource _id: 4ff46822f83222daf9000003, _type: nil>]
这显然失败了,因为每个where
子句都有一个匹配项。什么是正确的解决方案?有没有办法and
进行嵌入式文档查询?