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 具有写入权限的所有资源(应该没有)

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

这显然失败了,因为每个where子句都有一个匹配项。什么是正确的解决方案?有没有办法and进行嵌入式文档查询?

4

2 回答 2

1

尝试这个

Resource.where(:permissions.matches => {:write => true, :user_id => a.id}).all
于 2012-07-04T19:23:50.663 回答
-1

试试这个:

Resource.Permission.where(write: true,user_id: a.id)

于 2012-07-04T18:12:26.950 回答