views:

52

answers:

1

Is there an easy way to get all attributes of a Mongoid document, including those of embedded documents?

For example, if I have the following documents:

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

class PhoneNumner
  include Mongoid::Document
  embedded_in :person, :inverse_of => :phone_numbers
  field :number
end

I would like to get a Person's attributes and phone numbers like this:

{ :name => "Jenny", :phone_numbers => [{ :number => '867-5309' }, { :number => '867-5309' }] }
+2  A: 

Since embedded documents are really just other attributes on the parent document, you can get to them like so:

person = Person.create
person.phone_numbers.create(:number => "123-456-7890")
person.attributes
# => {"_id"=>"4c48ff26f7e2da3704000001",
#    "phone_numbers"=>
#     [{"number"=>"123-456-7890", "_id"=>"4c48ff26f7e2da3704000002"}]}
bernerdschaefer
Right. I'm on an older version of Mongoid which doesn't have this functionality. Thanks.
nicholaides