根据 habtm 关联对模型元素进行排序

发布于 2024-12-23 07:01:22 字数 107 浏览 1 评论 0原文

我必须对名为附​​件和由 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2024-12-30 07:01:22

一种简单且相对有效的方法是添加 计数器缓存< /a> 到您的附件 模型。计数器缓存将存储并保持 attachments 表上列中关联的数量,因此您可以执行 Attachment.order( 'user_attachments_count DESC' )

不幸的是,HABTM 不支持计数器缓存,因此您必须在其他两个模型之间弹出一个“中间人”模型才能访问连接表。

另一种方法(但性能较差)是简单地使用:

 @attachments = Attachment.includes(:users)
 @sorted      = @attachments.sort_by {|r| r.to_a.size }.reverse!

好吧,如果它不适合,你总是可以开始为 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 your attachments table, so you could do Attachment.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 :

 @attachments = Attachment.includes(:users)
 @sorted      = @attachments.sort_by {|r| r.to_a.size }.reverse!

Well, if it doesn't fit, you can always start sweating over a SQL query...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文