Mongoid, how to order_by through a references_one association (and subsequent associations)?

大城市里の小女人 提交于 2019-12-12 09:45:04

问题


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

So simply puts, we have collection of houses that are associated to an owner, and the owner can have a colored hat.

I can simply sort the house by their number:

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

But what I want is ordering the house, by the name of their owner, ideally I would like to write:

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

But it does not work...

And even further I would like to be able to sort the 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


回答1:


Dot notation is possible only for embedded documents, but you have 2 collections - houses and owners. In one of the Owner records in MongoDB you have only field house_id, in one of the House records you dont have any connection to Owner model. So the only way is to fetch all Houses and then to sort achieved collection using Enumerable#sort.




回答2:


ways to do this would be: - embed the owner name as string in the house doc. The house object would have both a owner_id (so that you can fetch full owner doc) and an extra field with just the owner name as string. You only need to change the name when changing the owner_id and that can be done in 1 update so it is consistent. Using this it will be a very efficient query since it doesnt need to look across collections and docs for reads. Downside is a bit more mem used.

  • have the owner object reference the house, since the owner "owns". Then you can query owner sorted by name, then fetch the reference house documents that you will get in the correct order. This has the downside of doing many individual queries.

  • one extreme solution is to embed all those docs: hat inside owner, owner inside house.

best, AG



来源:https://stackoverflow.com/questions/6452000/mongoid-how-to-order-by-through-a-references-one-association-and-subsequent-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!