【发布时间】:2011-10-01 22:25:36
【问题描述】:
我在 Rails 应用程序中嵌入了一个 one to one model 的 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,在 User 模型中是一个 Arry,其中包含多个元素(在本例中为 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" : "luca.soave@gmail.com",
"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 的循环。数组元素并退出,这也意味着最后一个元素在创建结束时保存到数据库中!方法,
...但我不知道如何解耦...
你有什么建议吗?
【问题讨论】:
标签: ruby-on-rails ruby mongodb mongoid nosql