Skip to content

Instantly share code, notes, and snippets.

@deevis
Created January 14, 2013 01:16
Show Gist options
  • Save deevis/4527120 to your computer and use it in GitHub Desktop.
Save deevis/4527120 to your computer and use it in GitHub Desktop.
ActiveRecord - group by with count and having
To perform this SQL statement:
-----------------------------------------------------------------------------------
select term_id, info_type_id, count(*) from item_feedbacks ifb, items i
21where ifb.item_id = i.id and i.source = 'Imgur'
group by term_id, info_type_id having count(*) > 15 order by count(*) desc ;
Here's the RoR ActiveRecord equivalent:
-----------------------------------------------------------------------------------
l=ItemFeedback.select("term_id, info_type_id, count(*) as count")
.joins(:item,:info_type,:term)
.where("items.source = ?", "Imgur")
.group("term_id,info_type_id")
.having("count > 15")
.order("count desc")
It is important to note that even thought ItemFeedback does not normally have a method 'count', but that it each ItemFeedback returned in the list will have a 'count' method which returns the correct value.
l.first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment