I wrote an article like this before. [Rails] Ranking by number of likes
In addition to this content, I implemented pagination, so I will leave it as a memo. This time, we aim to implement pagination that displays 5 posts sorted in order of likes on one page.
--The posts table is posts
and the user table is users
.
--The intermediate table required for the like function is likes
.
--posts
・ users
・ likes
It is assumed that each table has been created.
--Pagination is implemented using a gem called Kaminari
post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :likes, dependent: :destroy
has_many :liked_users, through: :likes, source: :user
end
user.rb
class User < ApplicationRecord
has_many :posts,dependent: :destroy
has_many :likes, dependent: :destroy
has_many :liked_posts, through: :likes, source: :post
end
like.rb
class Like < ApplicationRecord
belongs_to :post
belongs_to :user
end
Kaminari
to Gemfile and bundle install
Gemfile
gem 'kaminari', '~> 0.17.0'
$ bundle install
app/controller/posts_controller.rb
def index
posts = Post.includes(:liked_users).sort {|a,b| b.liked_users.size <=> a.liked_users.size}
@posts = Kaminari.paginate_array(posts).page(params[:page]).per(5)
end
Here, the order is manipulated using a ruby method called sort
.
=> See here for sort
a.liked_users.size
and b.liked_users.size
represent the number of likes for each post.
That is, the number of likes of each post is compared and sorted in ascending order.
Since the variable posts
generated by the sort
method is array data, the method paginate_array
is used.
All you have to do is display it in the view.
app/view/posts/index.html
<% @posts.each do |post| %>
#abridgement
<% end %>
<%= paginate @posts %>
There are many methods I don't know yet.
-Array # sort (Ruby 2.7.0 Reference Manual) -Create pagination using [rails] kaminari -Create a pager for an array using kaminari
Recommended Posts