ny95
ny95

Reputation: 710

MongoID has_any_belongs_to_many Reference

I have two models

Developer

  has_and_belongs_to_many :founding_organizations, class_name: 'Organization'
  has_and_belongs_to_many :collaborating_organizations, class_name: 'Organization'

Organization

  has_and_belongs_to_many :founders, class_name: 'Developer'
  has_and_belongs_to_many :collaborators, class_name: 'Developer'

How can I make the Developer model code work without changing anything on the organization model. Right now when you create an organization and use organization.founders << current_developer everything works fine and the developers id is stored in a founders array on the organization but if you query current_developer.founding_organizations the response is empty, how can I achieve this workflow? I had this working in ActiveRecord with joining tables but I moved to MongoDB which has so far been 10x better, its just getting used to doing things differently that has me confused.

Upvotes: 1

Views: 72

Answers (1)

Bart
Bart

Reputation: 2656

Not sure if this is possible without changing Organization model. How about using inverse_of option?

 has_and_belongs_to_many :founding_organizations, class_name: 'Organization', inverse_of: :founders
 has_and_belongs_to_many :collaborating_organizations, class_name: 'Organization', inverse_of: :collaborators

 has_and_belongs_to_many :founders, class_name: 'Developer', inverse_of: :founding_organizations
 has_and_belongs_to_many :collaborators, class_name: 'Developer', inverse_of: :collaborating_organizations

You'll find more info here http://mongoid.org/en/mongoid/docs/relations.html#common

Upvotes: 2

Related Questions