Search code examples
postgresqlruby-on-rails-5

Grouping Hash Tags with same hashTag name


I am finding a problem in group hashtags: Any Solution?

here is my query statement: any help. def trending_tags(user)

@tags= HashTag.joins(:vibe_hash_tags).limit(10).where('hash_tags.created_at BETWEEN ? AND ?', 1.months.ago, Time.now).select("hash_tags.id, hash_tags.address as country, count(vibe_hash_tags.id) as vibes_hash_tags,COUNT(hash_tags.id)as hash_tag_count")
     .group('COUNT(hash_tags.name as hash_tag_name)')
 render :status => 200, :json => {:success => true, :result => { :trending_hash_tags => @tags}}
end

I would want to group it to this

{ "success": true, "result": { "trending_hash_tags": [

        {
            "id": 83,
            "country": "TV",
            "vibes_hash_tags": 2,
            "hash_tag_name": "money",
            "hash_tag_count": 2
        },
        {
            "id": 84,
            "country": "TV",
            "vibes_hash_tags": 3,
            "hash_tag_name": "grace",
            "hash_tag_count": 3
        }
    ]
}

}


Solution

  • I have been able to find a solution my question for grouping Hash Tags.

    def trending_tags
       @hash_tags= HashTag
      .select('hash_tags.name AS hash_tag_name, COUNT(hash_tags
      .id) AS hash_tag_count, hash_tags.address AS country, count(vibe_hash_tags.id) AS vibes_hash_tags')
      .joins(:vibe_hash_tags)
      .order('hash_tag_count DESC')
      .group('hash_tags
      .name, hash_tags.address').limit(10).where('hash_tags.created_at BETWEEN ? AND ?', 5.days.ago, Time.now)
     render :status => 200, :json => {:success => true, :result => { :trending_hash_tags => @hash_tags}}
        end