学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails5.1 | 30 | Webアプリケーション開発 | 商品登録ページにページネーションの実装(kaminari)

<<前  [TOP]  次>>


Railsでページネーションを実装するには、前回に説明した「will_paginate」と「kaminari」によるものがあります。
今回は商品登録ページに「kaminari」によるページネーションを実装していきます。


まずは「kaminiari」のインストールです。
「Gemfile」の最後に「gem 'kaminari'」と1行追加します。


【Gemfile】

source 'https://rubygems.org'


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.10'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.3.13', '< 0.5'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'coffee-script-source', '1.8.0'

gem 'rails-i18n'

gem 'will_paginate'

gem 'kaminari'



コマンドプロンプトで「shop」フォルダに移動して「bundle install」します。




次に、サンプルの商品を登録するためのスクリプトを作成します。
前回作成した「script」フォルダの中に「load_goods.rb」というファイルを新規作成します。


【script/load_goods.rb(新規作成)】

Good.transaction do

	(1..100).each do |i|

		Good.create(:goods_id => "000#{i}", :title => "サンプル商品#{i}", :description => "テスト#{i}",:image_url => "/assets/test01.jpg", :price =>"100.0", :date => "2018-03-05 08:20:00", :maker => "サンプルメーカー", :category => "おもちゃ")

	end

end



コマンドプロンプトで「shop」フォルダに移動して、「rails runner script/load_goods.rb」と入力し、スクリプトを実行します。



WEBrickを起動して、確認してみます。

100個の商品が追加されました。


goodsコントローラの「index()」メソッドに「page()」メソッドを呼び出すように記述します。


【app/controllers/goods_controller.rb】

class GoodsController < ApplicationController
  before_action :set_good, only: [:show, :edit, :update, :destroy]

  # GET /goods
  # GET /goods.json
  def index

    @goods = Good.page(params[:page]).per(10)

	respond_to do |format|
		format.html
		format.json { render json: @goods }
	end

  end

  # GET /goods/1
  # GET /goods/1.json
  def show
  end

  # GET /goods/new
  def new
    @good = Good.new
  end

  # GET /goods/1/edit
  def edit
  end

  # POST /goods
  # POST /goods.json
  def create
    @good = Good.new(good_params)

    respond_to do |format|
      if @good.save
        format.html { redirect_to @good, notice: '商品が登録されました。' }
        format.json { render :show, status: :created, location: @good }
      else
        format.html { render :new }
        format.json { render json: @good.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /goods/1
  # PATCH/PUT /goods/1.json
  def update
    respond_to do |format|
      if @good.update(good_params)
        format.html { redirect_to @good, notice: '商品の登録内容が更新されました。' }
        format.json { render :show, status: :ok, location: @good }
      else
        format.html { render :edit }
        format.json { render json: @good.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /goods/1
  # DELETE /goods/1.json
  def destroy
    @good.destroy
    respond_to do |format|
      format.html { redirect_to goods_url, notice: '商品を削除しました。' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_good
      @good = Good.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def good_params
      params.require(:good).permit(:goods_id, :title, :description, :image_url, :price, :date, :maker, :category)
    end
end



変更したindex()メソッドのみ抜粋します。

def index

    @goods = Good.page(params[:page]).per(10)

	respond_to do |format|
		format.html
		format.json { render json: @goods }
	end

end

「.per(10)」と記述することで、1ページに表示される商品数を設定しています。
設定しない場合はデフォルトの25件表示になります。


次にindexビューにページネーションのリンクを追加します。


【app/views/goods/index.html.erb】

<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>

<h1>Railsはじめてマート</h1>

<table>
  <thead>
    <tr>
      <th>商品画像</th>
      <th>商品ID</th>
      <th>商品名</th>
      <th>説明</th>
      <th>画像URL</th>
      <th>価格</th>
      <th>登録日</th>
      <th>メーカー</th>
      <th>カテゴリー</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @goods.each do |good| %>
      <tr>
	<td text-align:center;><img height="80" src="<%=h good.image_url %>"/></td>
        <td><%= good.goods_id %></td>
        <td><%= good.title %></td>
        <td><%= good.description %></td>
        <td><%= good.image_url %></td>
        <td><%= (good.price).to_i %></td>
        <td><%=h ((good.date).to_date).strftime('%Y年%m月%d日') %></td>
        <td><%= good.maker %></td>
        <td><%= good.category %></td>
        <td><%= link_to '詳細', good, class: 'btn' %></td>
        <td><%= link_to '編集', edit_good_path(good), class: 'btn' %></td>
        <td><%= link_to '削除', good, method: :delete, data: { confirm: '本当に削除してもよろしいですか?' }, class: 'btn' %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to '商品登録', new_good_path, class: 'btn' %><span>  </span><%= link_to '注文を見る',{:action=>"index", :controller=>"orders"}, :class => 'btn' %>
<br>
<br>
<%= paginate @goods %>



追記したのは次の1行です。

<%= paginate @goods %>



最後にページネーションを日本語化します。
「config」フォルダの「locales」フォルダの中に「kaminari_ja.yml」というファイルを新規作成します。
内容は以下の通りです。


【config/locales/kaminari_ja.yml】

ja:
  views:
    pagination:
      first: "&laquo; 最初"
      last: "最後 &raquo;"
      previous: "&lsaquo; 前"
      next: "次 &rsaquo;"
      truncate: "..."



これでページネーションが日本語化されました。
確認してみます。





↓↓クリックして頂けると励みになります。


<<前  [TOP]  次>>