我希望对精选文章的标题进行分组、排序和计数。我选择了我的文章组如下:
@articles = Article.find(:all, :where("distance < ?", specified_distance))
在这里,我想对 @articles 中包含 的文章标题(不是 的所有 文章)进行分组、排序和计数,以便在 View 中使用(如下):

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

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

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

rails sorting blog posts by title

编辑/

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

最佳答案

在模型中:

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")
}

在 Controller 中:
@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

关于ruby-on-rails - 如何计算对象中字符串的出现次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6915583/

10-12 17:17
查看更多