Previously, I implemented the ranking function by referring to this article of Qiita ( Easy ranking function with Rails ). was. I was able to implement it successfully, but I faced the following problems.
@posts = Post.find(Like.group(:post_id).order('count(post_id) desc').pluck(:post_id)).page(params[:page])
When combined with kaminari's page method, it will be as above, but this will cause the following error.
Therefore, we will introduce the ranking function that can be combined with the page method without any problem.
--The table name of the article is posts ――Like table name is likes --You have already implemented the Like function and have an association between posts and likes.
@posts = Post.joins(:likes).group(:post_id).order('count(post_id) desc')
This is OK! I will explain one by one.
Post.joins(:likes) #Inner join the posts and likes tables
group(:post_id) #post_Divide groups into those with the same id
order('count(post_id) desc') #Post it_Sort in descending order of id
This completes the ranking function. As shown below, adding the page method to the end of the code does not cause an error, and I think the pagination function is working.
@posts = Post.joins(:likes).group(:post_id).order('count(post_id) desc').page(params[:page])
--Easy ranking function with Rails
https://qiita.com/mitsumitsu1128/items/18fa5e49a27e727f00b4
Recommended Posts