查询嵌入文档匹配多个属性

时间:2012-07-04 16:06:54

标签: ruby-on-rails ruby mongodb mongoid

我有以下结构:

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

2 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:-1)

试试这个:

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