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

Ruby on Railsのkaminari導入手順

Posted at

Railsのgemであるkaminariを導入します。

Gemfileに'kaminari'を記載

Gemfile
gem 'kaminari'

インストールする

コマンドライン
$ bundle install

scaffoldでデータ用のモデル等を作成する

コマンドライン
$ rails g scaffold data_page data:text

マイグレーションする

コマンドライン
$ rails db:migrate

ダミーデータを入れる

db/seed.rb
data = ['one','one','one','one','one','one','one','one','one','one','one','one','one']

for i in 1..100 do
  DataPage.create date:data.sample
end
コマンドライン
$ rails db:seed

kaminariの設定ファイルを作成

コマンドライン
$ rails g kaminari:config

設定ファイルの編集

config/initializers/kaminari_config.rb
# frozen_string_literal: true
Kaminari.configure do |config|
  config.default_per_page = 10 #1ページに表示される数
  # config.max_per_page = nil #1ページの最大表示数
  config.window = 3            #現在のページの左右に表示する数
  # config.outer_window = 1
  # config.left = 0
  # config.right = 0
  # config.page_method_name = :page
  # config.param_name = :page
  # config.params_on_first_page = false
end

コントローラーの修正

app/controllers/data_pages_controller.rb
  def index
    #修正前 @data_pages = DataPage.all
    @data_pages = DataPage.page params[:page]
  end

ブラウザに表示されるindexファイルの修正

app/views/data_pages/index.html.erb
<p id="notice"><%= notice %></p>

<h1>Data Pages</h1>

<

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th>Create at</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @data_pages.each do |data_page| %>
      <tr>
        <td><%= data_page.id %></td>
        <td><%= data_page.date %></td>
        <td><%= data_page.created_at %></td>
        <td><%= link_to 'Show', data_page %></td>
        <td><%= link_to 'Edit', edit_data_page_path(data_page) %></td>
        <td><%= link_to 'Destroy', data_page, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>
<%= paginate @data_pages %>
<br>
<%= link_to 'New Data Page', new_data_page_path %>

ブラウザで確認するとこんな感じです。

スクリーンショット 2019-06-11 22.13.08.png

それでは!!

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?