Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails model with Mongoid Embedded and Standalone

How would I create a Mongoid model that has the ability to be saved in it's own collection, and be embedded in another document?

like image 341
demersus Avatar asked Jun 13 '12 23:06

demersus


1 Answers

The short answer: you can't.

When you use an embedded relationship between two Mongoid documents, this is because you don't want the child model in its own collection. An embedded document it literally that: embedded in its parent.

I'm not sure if you're new to Mongoid, so what you may actually be looking for is a referenced relationship, which behaves more like a traditional RDBMS relationship, where the child document stores a reference to the parent document's ID. The Mongoid documentation for this starts here.

It's pretty easy to switch between the two, given these embedded models:

class Person
  include Mongoid::Document

  field :name
  embeds_many :phone_numbers
end

class PhoneNumber
  include Mongoid::Document

  field :area_code
  field :number

  embedded_in :person
end

You can just change the embeds_many and embedded_in, so it becomes:

class Person
  include Mongoid::Document

  field :name
  has_many :phone_numbers
end

class PhoneNumber
  include Mongoid::Document

  field :area_code
  field :number

  belongs_to :person
end

And it will just work. Now you'll be able to do things like query directly for phone numbers with statements like: PhoneNumber.where(:area_code => "212").

like image 138
theTRON Avatar answered Nov 15 '22 06:11

theTRON