Search code examples
ruby-on-railsruby-on-rails-3mongoidruby-on-rails-4mongoid3

Mongoid, how to keep relations in sync for common parent model?


I have three models:

Agency
has_many :owners
has_many :properties

Owner
belongs_to :agency
has_many :properties

Property
belongs_to :owner
belongs_to :agency

The agency.properties relation should refer to all properties that all owners have, but when I create a property inside an owner, the agency.properties relation is not created. I want this relation to be automatically fulfilled, as well as deleted when the owner or the property is deleted.

How can I achieve this behavior with mongoid?


Solution

  • As this is a pretty specific use case, there is no way to 'automatically' do this using mongoid 'out of the box'. What I would suggest you is to have some before_save hooks, that would guarantee the state of your relations. You also, depending of your use case, Property could be a denormalized(embedded) object inside Owner and Agency.