Gem 发布用于分页的 gem - simple_paginate

yonggu · 2015年03月15日 · 最后由 mingyuan0715 回复于 2015年03月24日 · 2975 次阅读

最近手上的项目需要使用到分页,并且只需要在前一页和后一页的导航,不需要链接到的具体的某一页,第一页或者最后一页。will_paginate 和 Kaminari 有点过于复杂,并且它们都会发送两条 SQL 语句来实现分页。于是就做了simple_paginate来通过发送一条 SQL 语句来实现,具体说明请看下面来自 README 的内容:

simple_paginate

Simple pagination solution for previous and next page navigation.

Why simple_paginate

We saw some websites using will_paginate or kaminari for pagination, but they just need previous and next page navigation, will_paginate or kaminari is overqualified.

Pagination in databae sometimes is slow because

  1. it sends a sql with OFFSET to get collection
  2. it sends additional sql with COUNT to get total number of record.

simple_paginate eliminates the additional COUNT sql, make your pagination faster.

How simple_paginate works

will_paginate and kaminari uses page and per_page to calculate offset and limit, then send 2 sqls

SELECT * FROM posts OFFSET 20 LIMIT 10;
SELECT COUNT(*) FROM posts;

after getting total count, they can calculate total pages, then render page numbers, prev, next, first and last page links.

simple_paginate also uses page and per_page to calculate offset and limit, but it only sends 1 sql

SELECT * FROM posts OFFSET 20 LIMIT 11;

it fetches one more record (11 = 10 + 1) to calculate if there is a next page records, so it doesn't need to send COUNT sql.

Usage

Query Basics

## perform a paginate query:
@users = User.paginate(:page => params[:page])

Helpers

## render previous page link:
<%= link_to_previous_page @users, 'Previous' %>

## render next page link:
<%= link_to_next_page @users, 'Next' %>

## render previous page link and next page link
<%= simple_paginate @users

General configuration options

You can configure the following default values by overriding these values using SimplePaginate.configure method.

default_per_page    # 25 by default

There's a handy generator that generates the default configuration file into config/initializers directory. Run the following generator command, then edit the generated file.

% rails g simple_paginate:config

Customizing the pagination helper

SimplePaginate includes a handy template generator, To edit your paginator, run the generator first:

% rails g simple_paginate:views 
匿名 #2 2015年03月15日

:plus1:

同样是轮子,F1 赛车上的干胎跟湿胎还是有区别的

好像有问题吧?比如说要求每页显示 10 个用户信息,那我代码调用

@users = User.paginate(page: params[:page], per_page: 10)

@users.each do |u|
  link_to u.name, u
end

页面上就显示 11 个用户了?

@quakewang 这个问题现在已经解决了,但是@users.count还是会返回 11,有待解决。

这个轮子不错,count 锁表确实很影响性能。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号