trnc
trnc

Reputation: 21577

Many-to-Many relation using Mongoid database-design?

i try to implement the following database structure, but have problems understanding how to do so using mongoid:

I have a model Documents, a model DocumentTeam and a model Employees. Users can create documents and can choose employees, which get added to the DocumentTeam. This is where I'm atm:

class Document
  embeds_one :document_team
end

class DocumentTeam
  has_many :employees
  embedded_in :document
end

class Employee
  belongs_to :document_teams
end

so my question: how can i tell rails to automatically insert a chosen Employee into the the embedded DocumentTeam when creating a Document?

Furthermore I want to be able to list e.g. all briefings of a Employee by

Employee.first.documents

is this possible as well?

thanks advance!

Upvotes: 1

Views: 165

Answers (1)

rubish
rubish

Reputation: 10907

In mongoid you can not reference embedded documents. You can reference root documents from embedded documents, but not the other way around. i.e. you can not have belongs_to :document_teams in Employee. Also, as a side effect is that relations in embedded documents should be single sided. You can change you modeling to following to achieve what you want:

class Document
  embeds_one :document_team
end

class DocumentTeam
  has_and_belongs_to_many :employees, inverse_of: nil
  embedded_in :document
end

class Employee
  def documents
    Document.where('document_team.employee_ids' => self.id)
  end
end

This will let you use Employee.first.documents, but you can not treat it as a relation and go on doing things you can do with relations, like reassigning, pushing and pulling documents. You have to manage teams and employees relations through DocumentTeam but can access an employees documents directly for reading.

PS: Document id not a good name for class, I guess it may clash with Mongoid::Document in some scenario.

Upvotes: 1

Related Questions