[Rails 常用插件简介]will_paginate

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

一:安装

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

 


二:使用

Controller

  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中显示分页

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

 


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

  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

 




  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中

  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做了包装,并且新增几个特性,如下:

  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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值