2 years ago
#28420
HighOnRails
How to order users by the number of user's posts in a particular category
I have 3 models,
- User (has_many :posts)
- Post (Belongs_to :user, has_many :categories through: :posts_categories)
- Category (has_many :posts through: :posts_categories)
Now, I want to find and order all users who have submitted most posts in a category, how do I achieve this using Ransack search
Eg. For category 'Fashion' I want to fetch & order users by number of user's posts in fashion.
Desired result should give,
- Mark (7 posts in fashion)
- Dave (5 posts in fashion)
- Carla (4 posts in fashion) .. so on
Note: Would prefer a solution that is compatible with postgres
My ransack search in controller
@search = User.all.search(params[:q])
@searchusers = @search.result(distinct: true)
@findusers = @searchusers.joins(posts: :categories)
.where(categories: { id: params['q']['posts_categories_id_eq'] })
.group('users.id')
.order('count(posts.id) desc').page(params[:page]).per(12)
Note: This works perfectly well in SQLite but fails in PG with below error 'PG::Error: SELECT DISTINCT, ORDER BY expressions must appear in select list'
ruby-on-rails
postgresql
associations
rails-activerecord
ransack
0 Answers
Your Answer