[RUBY] Arrange posts in order of likes on Rails (ranking)

Overview

When I searched for rails like rankings on the net, I found an article that ranked posts with one or more likes by internal join using join, but I could not find an article ranking including those with 0 likes. I've done my best to implement it, so I'll scribble it to deepen my understanding.

Premise

Question model (post) Like model

Implementation

@questions= Question.left_outer_joins(:likes).group('questions.id').select('questions.*, COUNT(likes.*) AS likes_count').distinct.reorder(likes_count: :desc).limit(100)

Commentary ...?

  1. Outer join the likes table to the Question model with left_outer_joins (: likes) Use outer joins because Questions that are not liked as inner joins using the joins method are excluded.

  2. Group the tables joined in 1 by questions.id Questions that are liked are grouped together

  3. Specify the data to be returned by the select statement (all questions table and likes_count)

  4. Remove duplicate data with distinct.

  5. Important here! Sort in descending order of likes_count with reorder method If it is the order method, the default order of the Questions table (new registration order) will be applied. Rewrite the order with the reorder method

  6. Use the limit method (if you like) to limit the number of data acquisitions to 100.

Finally

Honestly, it's an implementation that has a lot of vague understanding and is managed, so it may be wrong or inefficient. .. I would appreciate it if you could tell me implicitly. ..

The Rails guide is very easy to understand about the ActiveRecord query interface around here. By all means for reference

Recommended Posts