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.
gem 'will_paginate'
gem 'bootstrap-will_paginate'
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
post.rb
def self.sort_like
Post.all.sort{|a,b| b.liked_users.count <=> a.liked_users.count}
end
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'
<% @posts.each do |post|%>
<%= post.XXX %>
<% end %>
<%= will_paginate @posts %>
https://qiita.com/Kazuhiro_Mimaki/items/1f8e851b957f511c88e9 https://qiita.com/nakamurau1@github/items/13e081fcba1af0ca399f
Recommended Posts