如何计算对象中字符串的出现次数

时间:2011-08-02 16:49:07

标签: ruby-on-rails ruby ruby-on-rails-3

我希望对选择文章的标题的出现进行分组,排序和计数。我选择了以下文章:

@articles = Article.find(:all, :where("distance < ?", specified_distance))

在此,我想对@articles(不是所有文章)中包含的文章标题进行分组,排序和统计,以供用于一个观点(如下):

New York Yankees (3 Articles)
Boston Red Sox (1 Article)
Chicago Cubs (8 Articles)

这不是通过多对多的使用,而是严格的字符串比较,分组,计数。我不确定怎么做。在Rails中有这样做的标准做法吗?

这与用户要求的类似,但略有不同:

rails sorting blog posts by title

EDIT /

我必须仅使用@articles(而不是上面显示的物理查询),因为查询通常会发生变化,除此之外要复杂得多。因此,我的解决方案必须引用/ @articles

3 个答案:

答案 0 :(得分:1)

模特:

scope :articles_up_to, lambda { |distance| where("distance < ?", distance) }

scope :article_counts_up_to, lambda { |distance|
  articles_up_to(distance)
    .select("COUNT(*) AS count, title")
    .group("title")
    .order("count DESC")
}

在控制器中:

@article_counts = Article.article_counts_up_to(specified_distance)

编辑: 有关范围的这篇文章可能会有所帮助:http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html

答案 1 :(得分:1)

好的,我知道你想使用@articles,简而言之,这是一个(非常混乱的)解决方案,它不涉及更改模型或构建新的SQL查询:

@article_counts = @articles
  .group_by(&:title)
  .map { |a| {:title => a[0], :count => a[1].size} }
  .sort { |a1,a2| a2[:count] <=> a1[:count] }

答案 2 :(得分:0)

您可以使用一组方法:

http://railscasts.com/episodes/29-group-by-month