在 Rails 中对模型进行排名的最佳方法是什么
假设我有一个使用 Rails 和 MySQL 的博客应用程序的 Posts
和 Comments
。
我想按评论数量对帖子进行排名。 (注:不只是排序,而是得到他们实际的第一、第二、第三排名)。
另外,给定一个帖子,我希望能够获得它的排名,而无需将所有帖子加载到 Rails 中并搜索它们。
例如“这篇文章的评论数量排名#372”
最后,如果两个帖子的评论数量相同,那么它们应该具有相同的排名 - 所以平局是可以的。
我在 MySQL 中似乎有一些聪明的解决方案,例如这篇文章: 在 MySQL 中对结果进行排名时如何处理平局?< /a>
我想知道是否有一个更简单的解决方案,可以通过规范 posts 表上附加字段中的一些数据来实现。
有没有人看到一个好的方法?
Let's say I have Posts
and Comments
for a blog app using Rails and MySQL.
I want to rank Posts by number of comments. (Note: not just sort, but get their actual 1st,2nd,3rd rank).
Also, given a post, I want to be able to get it's rank without loading all Posts into Rails and searching through them.
e.g. "This post is ranked #372 by number of comments"
Finally, if two posts have the same number of comments, they should have the same rank - so ties are ok.
I've seem some clever solutions to this in MySQL, such as this post:
How do I Handle Ties When Ranking Results in MySQL?
I'm wondering if there is a simpler solution by normalizing some of the data in an additional field on the posts table.
Has anyone seen a good approach for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
进一步思考这一点,我认为有几种不同的方法可以添加此功能。
您可以将 Redis 添加到混合中并使用其排序集功能(如本文中的最高分示例)http://jimneath.org/2011/03/24/using-redis-with-ruby-on-rails.html
这可能是我认为最好的设计。您将分析部分与数据收集部分分开,并使用 Redis 最擅长的部分。
另一种方法是创建一个记录 post_id 和评论数的 PostRanking 模型。您可以为其设置默认范围,以按评论数量降序排序并轻松查询。
Thinking more about this, I think there are few different ways you can go about adding this functionality.
You can either add Redis to the mix and use its sorted set functionality ala the top score example in this post, http://jimneath.org/2011/03/24/using-redis-with-ruby-on-rails.html
This would probably be the best design, in my opinion. You divorce the analysis part from the data gathering part and you use redis what it's best at.
Another way is to create a PostRanking model that records the post_id and the comment count. You can put a default scope on this to sort by number of comments in descending order and query it easily.
此问题看起来与
:counter_cache
关联选项给出的示例相同。看一下。
This problem looks identical to the example given for the
:counter_cache
association option.Take a look.