[RUBY] Pagination sorted by number of likes

Introduction

This is a method of adding a pagination function after sorting the number of likes in descending order. I had a hard time implementing it, so I will leave it as a memorandum.

procedure

install gem

gem 'will_paginate'
gem 'bootstrap-will_paginate'

Define an association

post.rb


  belongs_to :user
  has_many   :likes,    dependent: :destroy
  has_many   :liked_users, through: :likes, source: :user

user.rb


  has_many :likes,    dependent: :destroy
  has_many :liked_posts, through: :likes, source: :user
  has_many :posts,    dependent: :destroy

like.rb


  belongs_to :post
  belongs_to :user

Define a class method

post.rb


  def self.sort_like
    Post.all.sort{|a,b| b.liked_users.count <=> a.liked_users.count}
  end

Reflect on the controller

post.controller


 @posts = Post.sort_like.paginate(page: params[:page],per_page: (Number you want to display on one page))

The paginate method is not available by default on arrays. Create a file under config / initializers and add require'will_paginate / array'.

will_pagenate.rb


require 'will_paginate/array'

Display in view

<% @posts.each do |post|%>
  <%= post.XXX %>
<% end %>
<%= will_paginate @posts %>

Articles that I used as a reference

https://qiita.com/Kazuhiro_Mimaki/items/1f8e851b957f511c88e9 https://qiita.com/nakamurau1@github/items/13e081fcba1af0ca399f

Recommended Posts

Pagination sorted by number of likes
[Rails] Ranking and pagination in order of likes
[Rails] Sort the post list by date or number of likes using the pull-down box
Implementation of pagination function
About truncation by the number of bytes of String on Android
Simplified version of number calculation by collecting information in an instance