2011-07-09 53 views
0

我在一個Rails應用程序嵌入one to one model一個mongoid(用戶 - >監視列表):爲什麼這個Mongoid文檔只能保存一個孩子?

class User 
    include Mongoid::Document 

    field :name, :type => String 
    field :email, :type => String 

    embeds_one :watchlist 

    def self.create_with_omniauth(auth) 

    conn = FaradayStack.build 'https://api.github.com' 
    resp = conn.get '/users/octocat/watched' 

    create! do |user| 

     user.name = auth["user_info"]["name"] 
     user.email = auth["user_info"]["email"] 

     resp.body.each do |repo| 
     user.build_watchlist(html_url: "#{repo['html_url']}") 
     end 
    end 
    end 
end 

class Watchlist 
    include Mongoid::Document 

    field :html_url 

    embedded_in :user 
end 

現在resp.body,在用戶模型(在此情況下2),其包含多個元素的阿利:

ruby-1.9.2-p136 :061 > pp resp.body.length 
2 
=> 2 
ruby-1.9.2-p136 :054 > resp.body.each do |repo| 
ruby-1.9.2-p136 :055 >  pp repo['html_url'] 
ruby-1.9.2-p136 :056?> end 
"https://github.com/octocat/Hello-World" 
"https://github.com/octocat/Spoon-Knife" 

,我希望在數據庫中保存在self.create_with_omniauth結束(AUTH)方法,反正我只是得到一個嵌套的「監視列表」孩子:

> db.users.find() 
{ 
"_id" : ObjectId("4e1844ee1d41c843c7000003"), 
"name" : "Luca G. Soave", 
"email" : "[email protected]", 
"watchlist" : { "html_url" : "https://github.com/octocat/Spoon-Knife", 
       "_id" : ObjectId("4e1844ee1d41c843c7000002") } 
} 
> 

很確定這部分代碼出了點問題:

resp.body.each do |repo| 
    user.build_watchlist(html_url: "#{repo['html_url']}", description: "#{repo['description']}") 
    end 

......這可能是n的cicles。數組元素和退出,這也意味着最後一個元素在創建結束時保存到數據庫中!方法,

...但我已經不是如何去耦那......

你有建議的想法?

回答

1

我剛剛得到一個嵌套的「監視列表」的孩子。

你只獲得了一個監視列表,因爲這是你告訴Mongoid您有:

class User 
    embeds_one :watchlist # only one watchlist 
end 

如果你想要一個以上的監視列表,你需要改變你的模型:

class User 
    embeds_many :watchlists 
end 
+0

非常感謝。不知道如何,我被鎖在想着一個孩子嵌套對象(有很多條目的數組...),而不是一個簡單的「嵌入式一對多」關係......偉大的幫助! –

1

如果您使用與您所尋找的系列匹配的字詞,它會有所幫助

embeds_many:手錶 或 has_one:watchlist(但類的Watchlist將依次embeds_many:手錶)

相關問題