[Rails 常用插件简介]will_paginate

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

一:安装
 ruby script/plugin install svn://errtheblog.com/svn/plugins/will_paginate  


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


如我们以前的find一样

在View中显示分页
<%= will_paginate @posts %>


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


    class Post < ActiveRecord::Base
      class<<self
          def per_page
            50
          end
      end
    end


2:) 在controller中
@posts = Post.paginate :page => params[:page]||1, :per_page => 50


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

will_paginate 对原有的find做了包装,并且新增几个特性,如下:
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 属性是必须的

你可能感兴趣的:(SVN,Ruby,Rails,ActiveRecord)