我在一個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。數組元素和退出,這也意味着最後一個元素在創建結束時保存到數據庫中!方法,
...但我已經不是如何去耦那......
你有建議的想法?
非常感謝。不知道如何,我被鎖在想着一個孩子嵌套對象(有很多條目的數組...),而不是一個簡單的「嵌入式一對多」關係......偉大的幫助! –