質問

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?

役に立ちましたか?

解決 2

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.

他のヒント

You could also write something like:

Agency
has_many :owners

Owner
belongs_to :agency
has_many :properties

Property
belongs_to :owner

And then add an instance method in your Agency model:

def properties
 owners.map(&:properties).flatten.uniq
end

However, this approach will query your database to retrieve the owners and then will query your DB again once per each owner to retrieve each owner's properties.

Hope this could help.

EDIT

There is another solution which implies just 2 queries:

def properties
 Property.where({:owner_id.in => owner_ids})
end

PROS:

It uses only two queries.

It returns a Mongoid Criteria (the previous solution returned an array). Thus you can chain scopes and so on ( i.e. my_agency.properties.sold #if you have defined a sold scope)

CONS:

This code seems less readable.

Additionally it's less maintainable. If you change the foreign key in the Owner-Property relation you should update this method (Property.where({:foreign_key...}) or you change the way an owner has many properties. The first option is still valid as long as each owner properties can be found with the instance method some_owner.properties.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top