包含引用文档ID的Mongoid查询文档

时间:2012-05-09 18:13:41

标签: ruby-on-rails-3 mongoid

我有一个小组模特。我想查询一个组以查看其中是否存在用户。通常使用嵌入式文档会更容易,但不幸的是,在这种情况下我无法做到这一点。在嵌入式场景中,我将执行以下操作。如何在引用的场景中执行此查询。

注意:** 我不想使用 habtm 关系。

查询

Matter.where(:'matter_counsels._id' => the_id)

class Matter
  include Mongoid::Document

  # Relationships
  has_many :matter_counsels # subclass of MatterRelationship
  has_many :matter_clients # subclass of MatterRelationship
  has_many :matter_opposing_parties # subclass of MatterRelationship
  has_many :matter_related_parties # subclass of MatterRelationship

end


class MatterRelationship
  include Mongoid::Document

  belongs_to :matter
end

1 个答案:

答案 0 :(得分:0)

我必须承认我上面的例子并不清楚。我和我的解决方案一起更新了问题。

class Matter
  include Mongoid::Document

  # Relationships
  has_many :matter_counsels # subclass of MatterRelationship
  has_many :matter_clients # subclass of MatterRelationship
  has_many :matter_opposing_parties # subclass of MatterRelationship
  has_many :matter_related_parties # subclass of MatterRelationship

  # Finder Scopes
  class << self

    # finds a type of matter relationship by user
    def for_user(user,type)
      user_id = user.id.to_s
      matter_ids = MatterRelationship.where(contact_id: user_id, _type: type).collect{ |i| i.matter_id.to_s }
      where(:_id.in => matter_ids)
    end

  end

end