开发环境:
OS:Windows XP
Ruby:Ruby1.9.1
Rails:Rails2.3.5
will_paginate:will_paginate2.3.11
(在命令行中运行 gem install mislav-will_paginate --source http://gems.github.com)
IDE:Rubymine2.0.1
DB:mysql5.0.9
本例在上一个例子(Ruby实践—简单数据库操作)的基础上实现分页,利用的是will_paginate插件
一、安装will_paginate
(在命令行中运行 gem install mislav-will_paginate --source http://gems.github.com)
二、修改enviroment.rb
引用"will_paginate",在
Rails::Initializer.run do |config|
end
之后添加 require 'will_paginate' ,否则运行时报错“method not found 'paginate' ”
三、修改product_controller.rb
修改 index 方法为如下:
def index # @products = Product.all @products = Product.paginate :page => params[:page]||1, :per_page => 2 respond_to do |format| format.html # index.html.erb format.xml { render :xml => @products } end end
#注:1是用户以http://localhost:3000/products 显示的第1页的数据;2是每页显示的记录数
@product_pages = Product.paginate :page => params[:page]||1, :per_page => 2
四、修改index.html.erb
添加如下引用
<%= will_paginate @products, :prev_label => 'pre', :next_label => 'next' %>
运行结果: