0
0

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 5 years have passed since last update.

kaminariのgemを用いたページネーションの実装方法

Posted at

ページネーションとは、長い文章を複数のページに分割して、各ページへのリンクを並べアクセスしやすくすること。
https://gyazo.com/7acc560088bf6fb2c04b90dda3b3d38e

実装手順

1.kaminariのGemをインストールしてサーバーを立ち上げ直す

Gemfileの最後の行にgemを記述する。

gem 'kaminari'

Gemをインストールする。

$ bundle install

rails s(サーバー)を立ち上げ直す。

rails s

2.コントローラファイルを編集する

kaminariのgemをインストールすることで使えるメソッド

1.pageメソッド


params[:page]

2.perメソッド
1ページあたりに表示する件数を指定するメソッドである。


per(1ページあたりに表示する件数)

3.「page」と「per」メソッドを利用して、コントローラに記述すると以下のようになる。


def index
    @tweets = Tweet.includes(:user).page(params[:page]).per(5).order("created_at DESC")
end

3.ビューファイルを編集する

paginateメソッド
ページネーションのリンクを表示したいときに使用するメソッドである。

paginate(インスタンス変数)

ビューファイルにはルビータグで囲って使用する。

<div class="contents row" >
    <% @tweets.each do |tweet| %>
      <div class="content_post" style="background-image: url(<%= tweet.image %>);">
        <%= simple_format(tweet.text) %>
        <span class="name"><%= tweet.name %></span>
      </div>
    <% end %>
  <%= paginate(@tweets) %>
</div>
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?