根据 habtm 关联对模型元素进行排序
我必须对名为附件和由 has_and_belongs_to_many 关联的用户进行建模。现在我必须找到以这样的方式排序的所有附件,首先显示具有关联的附件,然后显示那些没有关联的附件。我该怎么做?
I have to models named attachments and users associated by has_and_belongs_to_many. now i have to find all attachments sorted in such a way that attachments having association will be displayed first and then those with no association. How can i do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种简单且相对有效的方法是添加 计数器缓存< /a> 到您的
附件
模型。计数器缓存将存储并保持attachments
表上列中关联的数量,因此您可以执行Attachment.order( 'user_attachments_count DESC' )
。不幸的是,HABTM 不支持计数器缓存,因此您必须在其他两个模型之间弹出一个“中间人”模型才能访问连接表。
另一种方法(但性能较差)是简单地使用:
好吧,如果它不适合,你总是可以开始为 SQL 查询而烦恼......
One simple and relatively efficient way to do this would be to add a counter cache to your
Attachment
model. The counter cache would store and keep up-to-date the number of associations in a column on yourattachments
table, so you could doAttachment.order( 'user_attachments_count DESC' )
.Unfortunately HABTM does not support counter cache, so you would have to pop up a "middle-man" model between the two others just to get access to the join table.
Another way (yet with poor performance) is to simply use :
Well, if it doesn't fit, you can always start sweating over a SQL query...