开发者

Rails ActiveRecord distinct count of attribute greater than number of occurrences

开发者 https://www.devze.com 2023-01-26 19:14 出处:网络
I have a a table author_comments with a fields author_name, comment and brand id. I would like to get the number (count) of records where the author has more than N (2) reco开发者_如何学JAVArds for a

I have a a table author_comments with a fields author_name, comment and brand id.

I would like to get the number (count) of records where the author has more than N (2) reco开发者_如何学JAVArds for a given brand.

For example,

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

In this case my query should return 2 for brand 1 and 1 for brand 2.

I'm interested in the best performing option here, not getting all the records from the db and sorting through them in ruby, I can do this. I'm looking for best way using active record constructs or sql.

Update: Here is the SQL:

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

Should I just do find_by_sql?


You can define the same query using active record constructions:

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

or:

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


FanComment.group(:author_name).count
0

精彩评论

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