Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort ActiveRecord results by associated model count?

class Cafe < ActiveRecord::Base

  belongs_to :user

  has_many :posts, dependent: :destroy
  has_many :tags, dependent: :destroy
end

This is cafe.rb model

class Post < ActiveRecord::Base
  belongs_to :cafe
  belongs_to :user
end

and this is postq.rb. post is like replies.

I want to create new cafe array and sort it by cafe.posts.count. Finally, I will show top two cafes that have many replies.

I've tried some sorting codes like,

@cafe_by_posts = Cafe.joins(:post).order('posts.size dsc')

but it didn't work. The error said that cafe has no association with post. how can I sort ruby array by associated model count?

I'm not good at english, I'll appreciate your answers!

like image 738
Sangwoo Park Avatar asked Feb 11 '16 05:02

Sangwoo Park


2 Answers

Hey in mysql you can directly used like

@cafe_by_posts = Cafe.joins(:posts).group("posts.cafe_id").order('count(posts.cafe_id) desc')

You can directly select Top 2 using limit

 @cafe_by_posts = Cafe.joins(:posts).group("posts.cafe_id").order('count(posts.cafe_id) desc').limit(2)
like image 134
Vishal JAIN Avatar answered Sep 27 '22 01:09

Vishal JAIN


Relation name is posts not post, look:

has_many :posts, dependent: :destroy

Ordering should be done by SQL constraint. There is no dsc sort order in MySQL, it is desc. So, here you go:

 @cafe_by_posts = Cafe.joins(:posts)
                      .group('posts.cafe_id')
                      .order('COUNT(posts.cafe_id) DESC')
                      .limit(2) # to retrieve only 2 topmost records
like image 20
Aleksei Matiushkin Avatar answered Sep 23 '22 01:09

Aleksei Matiushkin