Reputation: 423
Three models
Tags has many Posts through PostTags
so what i need is to get all the name of tags which has maximum number of posts with the count
Upvotes: 2
Views: 3033
Reputation: 1034
As simple as that, it will work for rails 3 and rails 4
Post.joins(:tags).group("tags.name").count
Upvotes: 4
Reputation: 507
Following code should satisfy your needs:
Tag
.select('tags.name, COUNT(posts.*) AS posts_count')
.joins(:posts)
.order('posts_count DESC')
.group('tags.name')
.group_by(&:posts_count)
Upvotes: 3