ITeye博客

[Rails 常用插件简介]will_paginate

夜鸣猪 · 2008-05-10 13:34 · Markdown

Rails2.0中原pagination将被移出作为插件classic_pagination,will_paginate是个非常不错的替代方案

一:安装

[Copy to clipboard] [ - ]

CODE:

view plaincopy to clipboardprint?

  1. ruby script/plugin install svn://errtheblog.com/svn/plugins/will_paginate
 ruby script/plugin install svn://errtheblog.com/svn/plugins/will_paginate  

 

二:使用

Controller

[Copy to clipboard] [ - ]

CODE:

view plaincopy to clipboardprint?

  1. @posts = Post.paginate_by_board_id @board.id, :page => params[:page]||1
 @posts = Post.paginate_by_board_id @board.id, :page => params[:page]||1

 

如我们以前的find一样

在View中显示分页

[Copy to clipboard] [ - ]

CODE:

view plaincopy to clipboardprint?

  1. <%= will_paginate @posts %>
<%= will_paginate @posts %>

 

那么如何设定每页显示记录条数?paginate将会调用mode的per_page,譬如上面的Post将会调用Post.per_page.或者直接在paginate中加上per_page
1:) 在model中

[Copy to clipboard] [ - ]

CODE:

view plaincopy to clipboardprint?

  1. class Post < ActiveRecord::Base
  2. cattr_reader :per_page
  3. @@per_page = 50
  4. end
    class Post < ActiveRecord::Base
      cattr_reader :per_page
      @@per_page = 50
    end

 

[Copy to clipboard] [ - ]

CODE:

view plaincopy to clipboardprint?

  1. class Post < ActiveRecord::Base
  2. class<<self
  3. def per_page
  4. 50
  5. end
  6. end
  7. end
    class Post < ActiveRecord::Base
      class<<self
          def per_page
            50
          end
      end
    end

 

2:) 在controller中

[Copy to clipboard] [ - ]

CODE:

view plaincopy to clipboardprint?

  1. @posts = Post.paginate :page => params[:page]||1, :per_page => 50
@posts = Post.paginate :page => params[:page]||1, :per_page => 50

 

如果没有设定,将会使用默认值30

will_paginate 对原有的find做了包装,并且新增几个特性,如下:

[Copy to clipboard] [ - ]

CODE:

view plaincopy to clipboardprint?

  1. page           REQUIRED, but defaults to 1 if false or nil
  2. per_page       (default is read from the model, which is 30 if not overriden)
  3. total entries  not needed unless you want to count the records yourself somehow
  4. count          hash of options that are used only for the call to count
page           REQUIRED, but defaults to 1 if false or nil
per_page       (default is read from the model, which is 30 if not overriden)
total entries  not needed unless you want to count the records yourself somehow
count          hash of options that are used only for the call to count

 

注:page 属性是必须的

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。