0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

いいねの数で並べ替えてページネーション

Last updated at Posted at 2020-09-30

##はじめに
いいねの数を多い順で並べ替えた後、ページネーション機能を追加するやり方です。
実装するのに苦戦した為、備忘録として残しておきます。
##手順

####gemをインストール

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: (1ページに表示したい数))

paginateメソッドは配列にはデフォルトでは使えない。
config/initializersの下にファイルを作り、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

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?