--Ranking of user posts --Summing / averaging the evaluation points for posts, and ranking the posting points of the posting user. --Post score ranking (possible if you change the user part to post) ――The score ranking of the post by totaling / averaging the evaluation scores for the post
ruby 2.5.7 Rails 220.127.116.11 OS: macOS Catalina
-Build login environment with devise -Posting function that only logged-in users can do -Post editing function (update, delete)
Added to give a rating in the comments to the post.
$ rails g migration AddScoreToComments score:integer
class AddScoreToComments < ActiveRecord::Migration[5.2] def change add_column :comments, :score, :integer, default: 0 end end
If nothing is done, there will be a difference in points, so Described so that the score can be selected in view.
Evaluation:<%= f.number_field :score,min:1,max:5 %>
When giving the total value
<% @sum = 0 %> <% @post.comments.each do |comment| %> <% @sum += comment.score %> <% end %> <%= @sum %>
When calculating the average value
<% @average = 0 %> <% @post.comments.each do |comment| %> <% @average += (comment.score / @user.comments.count) %> <% end %> <%= @average %>
Now that we're ready, let's move on to the main topic.
controller The controller is the key.
Total value ranking: app/controllers/users_controller.rb
def rank @users = User. left_joins(:comments). distinct. sort_by do |user| hoges = user.comments if hoges.present? hoges.map(&:score).sum else 0 end end. reverse end
Mean ranking: app/controllers/users_controller.rb
def rank @users = User. left_joins(:comments). distinct. sort_by do |user| hoges = user.comments if hoges.present? hoges.map(&:score).sum / hoges.size else 0 end end. reverse end
view Can be displayed in descending order of each as shown below After creating app / views / users / rank.html.erb
<% @users.each do |user| %> <%= link_to user_path(user) do %> <%= user.name %><br> <% end %> <% end %>
get '/rank', to: 'users#rank'
[Easy ranking function with Rails] (https://qiita.com/mitsumitsu1128/items/18fa5e49a27e727f00b4) [Rails] Implementation of ranking function
This time I wanted to show the users who posted high scores, so Although it became such a description, It may not be very practical. However, if you use these rankings, Only for those who appreciate the score or only for those who have a low score I think it's a sales-friendly ranking because you can take an approach.
Also, if you want to implement word-of-mouth ranking etc. for the score ranking of posts, I think it will be a practical description.