レコードが数件のうちはScaffoldの機能だけで十分ですが、1,000件とかになるとメモリーの不足や転送速度の低下が発生し実用的でなくなってしまいます。そこで一定レコード毎に区切って表示をする方法を導入します。この機能を司っているのがPagenateというプラグインです。
1.プラグインwill_paginateのインストール
コマンド プロンプト |
c:\Ruby>gem sources -a http://gems.github.com
http://gems.github.com added to sources
Successfully installed mislav-will_paginate-2.3.11
1 gem installed
Installing ri documentation for mislav-will_paginate-2.3.11...
Installing RDoc documentation for mislav-will_paginate-2.3.11...
|
2.config/enviroment.rbの編集
最後尾(endのあと)に追加します。
/config/enviroment.rb |
# Be sure to restart your server when you modify this file
$KCODE = 'u'
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
:
:
end
gem "mislav-will_paginate", "2.3.11"
require "will_paginate"
|
3.一覧表示プログラムの修正
app/controllers/addresses_controller.rbのindexメソッドを修正します
/app/controllers/addresses_controller.rb |
class AddressesController < ApplicationController
# GET /addresses
# GET /addresses.xml
def index
@addresses = Address.paginate :page => params[:page],
:order => 'created_at DESC',
:per_page => 15
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @addresses }
end
end
:
:
end
|
4.一覧表プログラムの修正
app/views/index.html.erbにpagnateを追加します。
/app/views/index.html.erb |
<h1>Listing addresses</h1>
<table>
<tr>
<th>Namae</th>
<th>Yubin</th>
<th>Jusho</th>
<th>Denwa</th>
</tr>
<% for address in @addresses %>
<tr>
<td><%=h address.namae %></td>
<td><%=h address.yubin %></td>
<td><%=h address.jusho %></td>
<td><%=h address.denwa %></td>
<td><%= link_to 'Show', address %></td>
<td><%= link_to 'Edit', edit_address_path(address) %></td>
<td><%= link_to 'Destroy', address, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<div class="pagination_link">
<%= will_paginate @addresses %>
</div>
<br />
<%= link_to 'New address', new_address_path %>
|
5.WEBrickを再立ち上げして実行
ページネーション機能が動いているのが分かります。