Mongoid, how is order_by through the reference_one association (and subsequent associations)?

Simple model:

class hat embedded_in :owner field :color end class owner embedds_one :hat referenced_in :house field :name end class house references_one :owner field :number end 

It just poses, we have a collection of houses that are associated with the owner, and the owner can have a colored hat.

I can just sort the house by their number:

 House.all.order_by( [[ :number, :asc ]]) 

But I want to order a house, by the name of its owner, ideally I would like to write:

 House.all.order_by( [[ :'owner.name', :asc ]]) 

But this does not work ...

And even further, I would like to be able to sort houses by the color of the owner's hat

 House.all.order_by( [[ :'owner.hat.color', :asc ]]) 

Any idea how I can achieve this without rewriting everything if possible :)

thanks

Alex

+4
source share
2 answers

Spot recording is only possible for embedded documents, but you have 2 collections - houses and owners. In one of Owner's entries in MongoDB you have only the house_id field, in one of House's records you have no connection with the owner model. Thus, the only way is to get everything at Home, and then sort the resulting collection using Enumerable # sort.

+3
source

This can be done like this: - Insert the name of the owner in a line in the doc document. The home object will have both owner_id (so you can get the full owner’s document) and an additional field with just the owner’s name as a string. You need to change the name when owner_id changes, and this can be done in 1 update so that it is consistent. Using this, this will be a very effective query, since it does not need to view collections and documents for reading. The downside is a bit more used memory.

  • The owner of the object has a link to the house, as the owner "owns". Then you can request the owner, sorted by name, and then receive the documents of the reference house, which you will receive in the correct order. This has the disadvantage of performing many individual queries.

  • one of the extreme decisions is to include all these documents: a hat inside the owner, the owner inside the house.

better AG

+2
source

All Articles