Created
January 14, 2013 01:16
-
-
Save deevis/4527120 to your computer and use it in GitHub Desktop.
ActiveRecord - group by with count and having
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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