Mongoid,如何通过references_one协会(以及随后的协会)ORDER_BY? [英] Mongoid, how to order_by through a references_one association (and subsequent associations)?
问题描述
简单的模型:
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 :)
感谢
亚历
推荐答案
点符号只为嵌入文档是可能的,但你有2集 - 房屋和业主。
在MongoDB中所有者记录一个你只有场house_id在众议院一个记录你没有所有者模型中的任何连接。
所以,唯一的办法就是获取所有房屋,然后使用可枚举#排序排序实现集合。
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.
这篇关于Mongoid,如何通过references_one协会(以及随后的协会)ORDER_BY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!