开发者

Why does this Mongoid document only save one child?

I've a mongoid embedded one to one model in a Rails app (User --> Watchlist) :

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

Now resp.body, in User model is an Arry which contains several elements ( 2 in this case ):

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"

which I expect to save in the db at the end of self.create_with_omniauth(auth) method, anyway I just get one, nested "watchlist" child :

> 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") }
}
>

Pretty sure something goes wrong with this part of code:

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

... which probably cicles for the n. array elements and exit, wich also mean the last element is saved into the DB at the end of create! method,

... but I've not idea on how to decoupling that ...

Do you have a suggestion ?


I just get one, nested "watchlist" child.

You're only getting one watchlist because that's what you told Mongoid you have:

class User
  embeds_one :watchlist  # only one watchlist
end

If you want more than one watchlist, you need to change your model:

class User
  embeds_many :watchlists
end


it helps if you use the term matching the collection you seek

embeds_many :watches or has_one :watchlist (but class Watchlist will in turn embeds_many :watch)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜