【问题标题】:Why does this Mongoid document only save one child?为什么这个 Mongoid 文档只救了一个孩子?
【发布时间】: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


    【解决方案1】:

    我只得到一个嵌套的“监视列表”子级。

    你只得到一个监视列表,因为你告诉 Mongoid 你有:

    class User
      embeds_one :watchlist  # only one watchlist
    end
    

    如果您想要多个关注列表,则需要更改模型:

    class User
      embeds_many :watchlists
    end
    

    【讨论】:

    • 非常感谢。不知道怎么回事,我被锁定在考虑一个子嵌套对象(具有许多条目的数组......)而不是更简单的“嵌入一对多”关系......非常有帮助!
    【解决方案2】:

    如果您使用与您寻找的收藏相匹配的术语会有所帮助

    embeds_many :手表 要么 has_one :watchlist (但类 Watchlist 将依次嵌入 _many :watch)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 2023-04-08
      • 2021-11-08
      • 1970-01-01
      • 2023-01-26
      相关资源
      最近更新 更多