开发者

How to count occurrences of strings in objects

I'm looking to group, sort and count the occurrences of titles of a selection articles. I have selected my group of articles as follows:

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

Here out, I would like to group, sort and count the article titles that are included in @articles (not of all articles) for use in a view (as follows):

New York Yankees (3开发者_StackOverflow社区 Articles)
Boston Red Sox (1 Article)
Chicago Cubs (8 Articles)

This is not through usage of a many-to-many, it strictly string comparison, grouping, counting. I'm not sure how it is to be done. Is there a standard practice for doing this in Rails?

This is similar to what this user is asking for, but slightly different:

rails sorting blog posts by title

EDIT/

I must use @articles only (and not the physical query displayed above) because the query will often change and is much more complicated beyond that. So, my solution must refer to/from @articles.


In model:

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

In controller:

@article_counts = Article.article_counts_up_to(specified_distance)

Edit: This article on scopes may be helpful: http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html


Ok, I understand you want to use @articles, so briefly, here's a (really messy) solution which doesn't involve changing the model, or building new SQL queries:

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


There's a group by method that you can use:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜