Rails order user based on number of badges with Gem Merit

106 Views Asked by At

I have a problem ordering users based on numbers of badges he/she has collected. I'm using Gem Merit to make the badges system. so if I want to collect user's badges, the code would be user.badges that would convert to sql as

Merit::Sash Load (1.6ms)  SELECT  "sashes".* FROM "sashes" WHERE "sashes"."id" = ? LIMIT ?  [["id", 5], ["LIMIT", 1]]
Merit::BadgesSash Load (1.4ms)  SELECT "badges_sashes".* FROM "badges_sashes" WHERE "badges_sashes"."sash_id" = ?  [["sash_id", 5]]

in User model I include Merit and has_merit code as merit documentation said, and when I write users = User.where(id: user_ids).left_joins(:merit).order(is_verified: :desc).group(:id).order("count(badges.id) desc") it says errors because it cannot recognize either the merit or badges.id

How do I actually order the users based on who has the most badges? THank you!

1

There are 1 best solutions below

1
Abibullah Rahamathulah On

I never tried merit. But if u are able to get badges from user. then following query would give the USER_ID ==> BADGES_COUNT in descending order.

User.joins(:badges).group('users.id').order("count(badges.id) DESC").count