Rails ActiveRecord独特的属性计数大于出现次数

时间:2010-11-23 17:15:22

标签: ruby-on-rails performance activerecord

我有一个表author_comments,其中包含字段author_name,comment和brand id。

我想获得作者对特定品牌的记录数超过N(2)的记录数量(计数)。

例如,

author_comments

author_name      comment                 brand

joel             "loves donuts"             1

joel             "loves cookies"            1

joel             "loves oranges"            1

fred             "likes bananas"            2

fred             "likes tacos"              2

fred             "likes chips"              2

joe              "thinks this is cool"      1

sally            "goes to school"           1

sally            "is smart"                 1

sally            "plays soccer"             1

在这种情况下,我的查询应该为品牌1返回2,为品牌2返回1.

我对这里表现最好的选项感兴趣,没有从db获取所有记录并在ruby中对它们进行排序,我可以这样做。我正在寻找使用活动记录结构或sql的最佳方法。

更新: 这是SQL:

SELECT author_name, COUNT(*) AS author_comments
FROM fan_comments
WHERE brand_id =269998788
GROUP BY author_name
HAVING author_comments > 2;

我应该做find_by_sql吗?

2 个答案:

答案 0 :(得分:3)

您可以使用活动记录构造定义相同的查询:

FanComments.all(
  :select => 'author_name, count(*) as author_comments', 
  :group => 'author_name', 
  :having => 'author_comments > 2') # in rails 2

或:

FanComments.
  select('author_name, count(*) as author_comments').
  group('author_name').
  having('author_comments > 2') # in rails 3

答案 1 :(得分:1)

FanComment.group(:author_name).count