rails 按标题对博客文章进行排序 [英] rails sorting blog posts by title
问题描述
我意识到这可能很少发生(两个或多个用户具有相同的博客文章标题),但这是我的客户想要的,所以我必须弄清楚.
I realize that this could be a rare occurrence (that two or more users would have the same blog post title) but this is something my client wants so, I have to figure it out.
我有一个查询@blog_posts(这是对根据位置等更改的帖子的查询).我需要一种方法来列出所有帖子标题以及该标题在查询 @blog_posts
I have a query @blog_posts (which is a query on Posts that changes based on location, etc). I need a way to to list out all the posts titles and how many times that title occurs within the query @blog_posts
像这样:
How to clean a car (2)
I love baseball (1)
是否有分组和排序的标准做法?
Is there a standard practice for grouping and sorting?
总而言之,我需要计算查询中出现的次数 @blog_posts = Post.where(...)
(例如)——不是现有的所有帖子.
推荐答案
听起来您基本上想要计算出现次数:这个答案 可以适应您的目的.
Sounds like you basically want to count occurrences: this answer could be adapted to your purposes.
如果您使用的是 1.8.7 或更高版本,请考虑使用 group_by
:
If you're on 1.8.7 or newer, consider group_by
:
ruby-1.9.2-p180 :002 > posts = ["How to clean a car", "How to clean a car", "I love baseball"]
=> ["How to clean a car", "How to clean a car", "I love baseball"]
ruby-1.9.2-p180 :007 > posts.group_by {|e| e}.map {|k, v| {k => v.length}}
=> [{"How to clean a car"=>2}, {"I love baseball"=>1}]
这篇关于rails 按标题对博客文章进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!