SRDP
SRDP

Reputation: 423

How group by and get the count in has_many :through rails

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

Answers (2)

archit gupta
archit gupta

Reputation: 1034

As simple as that, it will work for rails 3 and rails 4

Post.joins(:tags).group("tags.name").count

Upvotes: 4

Alexaner Tipugin
Alexaner Tipugin

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

Related Questions