[Ruby on Rails] Posting score ranking function (whole display)

Target

--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

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina

Premise

-Build login environment with devise -Posting function that only logged-in users can do -Post editing function (update, delete)

Add column

Added to give a rating in the comments to the post.

Terminal


$ rails g migration AddScoreToComments score:integer

db/migrate/xxxxxxxxxxxxx_add_score_to_comments.rb


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.

erb:app/views/posts/show.html.erb


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
Supplement -Left_joins (: comments): Get all users associated with comments by saying left outer joins. If there is no comment, it is a method to get null. This explanation is easy to understand. [[Rails] What is a left outer join defined by the left_joins method? ](Https://pikawaka.com/rails/left_joins) -Distinct: A method for combining duplicate records into one, In this case, if there are two or more comments, the user will also get two or more, so Used to avoid duplication. ・ Sort_by do |user|: A method to sort the array in ascending order. As a value, substitute it under the conditions after if. -Map (&: score): A method that adds only the score value. This explanation is easy to understand. [The meaning of arr.map (&: id) that you often see in Rails](https://qiita.com/s_tatsuki/items/869af9c0c33d9d650f3f) -Reverse: Sort_by is used to sort in ascending order, so it is reversed. However, note that if the numbers are the same, they will be in the order of newest. I will update it again if I can solve it. -Hoges.size: The number of hoges is acquired. The average is calculated based on that number.

view Can be displayed in descending order of each as shown below After creating app / views / users / rank.html.erb

erb:app/views/users/rank.html.erb


<% @users.each do |user| %>
  <%= link_to user_path(user) do %>
    <%= user.name %><br>
  <% end %>
<% end %>

routing

config/routes.rb


get '/rank', to: 'users#rank'

Reference site

[Easy ranking function with Rails] (https://qiita.com/mitsumitsu1128/items/18fa5e49a27e727f00b4) [Rails] Implementation of ranking function

Summary

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.

Recommended Posts

[Ruby on Rails] Posting score ranking function (whole display)
[Ruby on Rails] Ranking display (total, average value)
[Ruby on Rails] Asynchronous communication of posting function, ajax
[Ruby on Rails] Introduced paging function
[Ruby on Rails] CSV output function
[Ruby on Rails] Comment function implementation
[Ruby on Rails] DM, chat function
Ruby on Rails for beginners! !! Post list / detailed display function summary
[Ruby on Rails] Follow function implementation: Bidirectional
[Ruby on Rails] Posting function that only logged-in users can post
[Ruby on rails] Implementation of like function
[Ruby on Rails] Logical deletion (withdrawal function)
Validation settings for Ruby on Rails login function
Implementation of Ruby on Rails login function (Session)
[Ruby on Rails] How to display error messages
Ruby on Rails Email automatic sending function implementation
[Ruby on Rails] Post editing function (update, delete)
[Ruby on Rails] Individual display of error messages
[rails] tag ranking function
Ruby on Rails Elementary
Ruby on Rails basics
Ruby On Rails Association
How to implement image posting function using Active Storage in Ruby on Rails
Ruby on Rails <2021> Implementation of simple login function (form_with)
Implementation of Ruby on Rails login function (devise edition)
[Ruby on Rails] Implementation of tagging function/tag filtering function
[Ruby on Rails] Post image preview function in refile
[Ruby on Rails] Search function (model, method selection formula)
Ruby on rails learning record -2020.10.03
Portfolio creation Ruby on Rails
Ruby on rails learning record -2020.10.04
Ruby on rails learning record -2020.10.09
Ruby on Rails config configuration
Ruby on Rails basic learning ①
[Ruby on Rails] about has_secure_password
Ruby on rails learning record-2020.10.07 ②
Commentary on partial! --Ruby on Rails
Ruby on rails learning record-2020.10.07 ①
Cancel Ruby on Rails migration
Ruby on rails learning record -2020.10.06
[Rails] Implement image posting function
Ruby on Rails validation summary
Ruby on Rails Basic Memorandum
Ruby on Rails Email automatic sending function setting (using gmail)
Ruby on Rails for beginners! !! Summary of new posting functions
[Ruby on Rails] Quickly display the page title in the browser
(Ruby on Rails6) Display of the database that got the id of the database
From Ruby on Rails error message display to Japanese localization
A note about the seed function of Ruby on Rails
[Ruby on Rails] Implement login function by add_token_to_users with API
How to display a graph in Ruby on Rails (LazyHighChart)
Ruby on Rails Overview (Beginner Summary)
[Ruby on Rails] yarn install --check-files
Ruby on Rails variable, constant summary
Installing Ruby + Rails on Ubuntu 18.04 (rbenv)
I want to add a browsing function with ruby on rails
Basic knowledge of Ruby on Rails
How to use Ruby on Rails
[Ruby on Rails] Add / Remove Columns
Ruby on Rails Japanese-English support i18n
(Ruby on Rails6) "Erase" posted content