开发者

Embed in many documents

class Person
  include Mongoid::Document
  field :name
  embeds_many :addresses
end

class Company
  include Mongoid::Document
  field :name
  embeds_many :addresses
end

class Address
  include Mongoid::Document
  emb开发者_高级运维edded_in :addressable, inverse_of :addresses
end

I tried something like this

company = Company.first
person = Person.first
address = Address.new

company.addresses << address
company.save
=>true

person.addresses << address
person.save
=>true

But I didn't found address embedded in person.But I found that it was embedded in company. Did anyone know why? Or Can't I embed address in multiple document.

Again while I reversed like this

person.addresses << address
person.save
=>true

company.addresses << address
company.save
=>true

I found address was embedded in person not in company.. Any Ideas.


If clone() doesn't work you could create a new Address record based on the attributes of the old Address. This will be a new object and should successfully save.


Try to clone your address :

person.addresses << address
person.save
=>true

company.addresses << address.clone
company.save
=>true

All document even embedded are _id so it not new_record in second case if you ton clone it.


This might help you,

company.addresses.new.attributes = address.attributes 
company.save

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜