I am creating an application that allows you to browse and search for articles related to subsidies. Since we were able to implement the like function this time, we implemented a ranking function that arranges articles in descending order of the number of likes. Described for memorandum and revenge.
Ruby on Rails '6.0.0' Ruby '2.6.5'
-User management function implemented (User table) ・ Article posting / viewing function implemented (Article table) ・ Like function implemented (Like table)
Since it is only necessary to be able to retrieve articles from multiple articles in descending order of the number of likes, we will describe how to retrieve articles from the Article table.
I will describe the implementation method first and explain the contents.
def index @ranks = Article.find(Like.group(:article_id).order('count(article_id) DESC').limit(4).pluck(:article_id)) end
Article.find(~) --Use the find method to find and get the article specified in ().
Like.group(:article_id) --Records with duplicate article_id in Like table are sorted together.
order('count(article_id) DESC') --The count (article_id) data is sorted by DESC (descending order).
count(article_id) --This is a method to count the same article_id. We get the number of likes by counting the records stored in the Like table.
limit(4) ――It is a method to get the four from the top. This time I wanted to display up to 4th place, so I chose this expression.
pluck(:article_id) --If a list of column names is given as an argument, an array of values for the specified column will be returned with the corresponding data type.
I referred to this article! !! !! Thank you very much.
We were able to implement the article display in descending order of the number of likes, but we added it in the hope that it would be possible to display "1st place" for each article.
<% @ranks.each.with_index(1) do |article, i| %> <div class="card-group col-md-6 col-lg-3"> <span class="article-info"><i class="fas fa-crown"></i>No.<%= i %>Rank</span>
To display the ranking, I was able to display the ranking using ".with_index (1)".
This is a reference URL!