2012-05-09 115 views
0

我有一個組模型。我想查詢一個組來查看是否存在用戶。通常情況下,使用嵌入式文檔更容易,但不幸的是,在這種情況下,我不能這麼做。在嵌入式場景中,我會執行以下操作。如何在參考場景中執行此查詢。包含引用文檔ID的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 

回答

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 
相關問題