您的位置:首页 > 大数据 > 人工智能

Rails2中使用will_paginate插件进行分页

2008-03-05 22:04 405 查看
作者:老王

Rails(2.0.2)推荐的分页方式是will_paginate插件,以前的分页功能剥离为classic_pagination插件,但已不再维护。这两个插件都在:

svn://errtheblog.com/svn/plugins/

本文将介绍其基本用法。

开发环境是WindowsXP操作系统,编辑器是Netbeans。

这里使用《Web开发敏捷之道》中的Depot例子来说明will_paginate插件的基本用法,同时也算是复习。

--------------------------------------------------------------------------------

先创建一个Depot项目

File - New Project - Samples - Ruby - Depot Appliction

配置数据库连接


编辑database.yml文件,设置适当的数据库用户名,密码等信息

数据迁移

Depot Appliction - Migrate Database - To Current Version

--------------------------------------------------------------------------------

此时,一个可运行的Rails项目就算是创建好了。

--------------------------------------------------------------------------------

安装插件

利用Netbeans安装will_paginate插件:在Depot Appliction项目上点右键,选择Rails Plugins,然后加入新的Respositoies地址:

svn://errtheblog.com/svn/plugins/

此时,在New Plugins里就能看到will_paginate插件了,安装易如反掌。

注意:安装前要确保svn命令已经处于系统PATH系统环境变量之中,如果没有请先安装(链接)。

--------------------------------------------------------------------------------

will_paginate教程

以Depot中admin控制器的list方法为例,将其改为如下代码:

def list
@products = Product.paginate :page => params[:page], :per_page => 2
end

再创建其对应的模板文件(list.html.erb),内容如下:

<h1>Listing products</h1>

<table>
<tr>
<th>title</th>
<th>description</th>
<th>price</th>
</tr>
<% for product in @products %>
<tr>
<td><%=h product.title %></td>
<td><%=h product.description %></td>
<td><%=h product.price %></td>
</tr>
<% end %>
</table>

<%= will_paginate @products,
:inner_window => 1,
:outer_window => 1,
:prev_label => '上一页',
:next_label => '下一页'
%>

在Netbeans里按F6,运行此项目,就可以看到分页的效果了(http://localhost:3000/admin/list)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: