2013-03-10 108 views
1

我試圖通過它的id搜索嵌入的文檔,並將其返回。這是可能的,但只有在我看來,通過使用mongo來查找嵌入它的文檔,然後在ruby中搜索該文檔以獲取我之後的嵌入文檔。就像這樣:Mongoid找到嵌入的文檔

# commenter.rb 
    def post 
    # todo: find syntax do avoid double query 
    if user = User.any_of({'posts.commenter_ids' => self.id}).last 
     user.posts.where('commenter_ids' => self.id).last 
    end 
    end 

看似簡單,但我沒有發現任何東西我明明喜歡在谷歌/ SO搜索。

想法?

+2

請您提供您的模型? – 2013-03-18 18:18:10

回答

1

現在我在嵌入式文檔中包含以下功能。它要求您在嵌套關係上設置inverse_of選項。

# Returns the parent "embedded_in" relationship for this document 
# @return [Mongoid::Relations::Metadata] 
def self.parent_relationship 
    @parent_relationship ||= relations.values.find do |relation| 
    relation.macro == :embedded_in 
    end 
end 

# finds the document off of a root document. This method currently only works correctly if 
# you explicitly set the inverse_of value on the embedded_in relationship 
# @param [string | Moped::BSON::ObjectId] id 
def self.find_using_parent(id) 
    id = id.is_a?(Moped::BSON::ObjectId) ? id : Moped::BSON::ObjectId(id) 
    parent = parent_relationship.class_name.to_const.where("#{parent_relationship.inverse_of}._id" => id).first 
    if parent 
    parent.__send__(parent_relationship.inverse_of).find(id) 
    end 
end 
2

我用這個要點上我的嵌入式文件覆蓋find方法:https://gist.github.com/cblavier/7889042

,當我想用​​DelayedJob延遲嵌入文檔的方法(因爲DJ工人將使用查找(ID這是特別方便)進行反序列化這項工作)

+0

你是MVP的人!在多態嵌入的情況下仍然很難(在這種情況下,除了導出原始ID字符串/類型並使用適當的find_through方法外別無選擇) – 2017-04-08 14:23:58