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 ?
You’re only getting one watchlist because that’s what you told Mongoid you have:
If you want more than one watchlist, you need to change your model: